text string | label_name string | labels int64 |
|---|---|---|
in the string "word"
/// let mut fact = Fact::new('r','c',0,0,2);
/// fact.set_prior_key('o');
/// }
///
#[inline]
pub fn set_prior_key(&mut self, pk: char) {
self.prior_key = Some(pk);
}
}
/// Represents a symbolic pattern of an entity (String)
pub struct Pattern {
//... | Rust | 0 |
08S\xc6\
5\xe3\xb4[z\xc1\x12Z\xe8\x19>3\x95+\x9a\xf3\
\xf8v\x16\xc2\xe2\xdb\x06\x0a\xc3\xf2F\xd9\xf4t{\xb2\
\xfa\xba\xf1\x96\xf1\x03\xcebA\x97\x95'\xbc7\xfa\x83\
C\xcc\x1b\x9b\xbb]\x9a\x91\x90\xd1\x8co\xfa\xc2\xc8\xc9\
\xe0)+N\xa1\xec\x8c\xc06Yh\x0b\x7f\xae\xedy\
i\x9dK\xf8<So<\x81\xbb\xefy\x86\x92\xf6\x19\
\xfe]jf\xe3... | Python | 1 |
size,
data: Vec<Vec<char>>,
}
impl fmt::Display for Canvas {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let result = self.data.iter().fold(String::new(), |acc, row| {
let line = row.into_iter().collect::<String>();
format!("{}{}\n", acc, line)
});
... | Rust | 0 |
no_model.device), "B N C H W -> (B N) C H W"),
)
if return_dict:
# dino
dino_embeds_dict = DINOEmbedOutput(
last_hidden_state=vision_outputs.last_hidden_state,
pooler_output=vision_outputs.pooler_output,
)
return dino_... | Python | 1 |
Event<T: Config<I>, I: 'static = ()> {
AnchorCreated,
AnchorEdgeAdded,
AnchorEdgeUpdated,
}
#[pallet::error]
pub enum Error<T, I = ()> {
/// Access violation.
InvalidPermissions,
// Anchor handler already exists for specified resource Id.
ResourceIsAlreadyAnchored,
// Anchor handler doesn't exist f... | Rust | 0 |
consensus_handle => {
debug!(target: "BanklessBFT-runway", "{:?} Consensus task terminated early.", index);
},
_ = &mut exit => {},
}
info!(target: "BanklessBFT-runway", "{:?} Ending run.", index);
if consensus_exit.send(()).is_err() {
debug!(target: "BanklessBFT-runway... | Rust | 0 |
from django.shortcuts import render, redirect
from app01.models import Department, UserInfo, PhoneNumbers, MyAdmin
from app01.utils.page_nav import PageNav
from app01.srcs.forms.form import MyadminForm, MyadminFormEdit ,MyadminFormReset
def myadmin_list(req):
info = req.session.get("info")
# 获取session信息,未登录... | Python | 1 |
d+/(?:video/)?(?P<id>[^/?#&]+)'
_RETURN_TYPE = 'video'
class NexxIE(LazyLoadExtractor):
_module = 'yt_dlp.extractor.nexx'
IE_NAME = 'Nexx'
_VALID_URL = '(?x)\n (?:\n https?://api\\.nexx(?:\\.cloud|cdn\\.com)/v3(?:\\.\\d)?/(?P<domain_id>\\d+)/videos/byi... | Python | 1 |
ple
//!
//! ```no_run
//! extern crate futures;
//! //if you use the mail facade use the re-exports from it instead
//! extern crate mail_core;
//! extern crate mail_smtp;
//! #[macro_use] extern crate mail_headers;
//!
//! use futures::Future;
//! use mail_headers::{
//! headers::*,
//! header_components::Doma... | Rust | 0 |
'c> {
fn to_multipart(&self) -> Result<Multipart, Error> {
multipart_map! {
self,
(chat_id (text));
(document (raw));
(thumb (raw), optional);
(caption (text), optional);
(parse_mode (text), optional);
(reply_to_message_id (... | Rust | 0 |
, 1), (2, 1)],
"cells": ["36542", "4512", "3934"],
"aggregator": "AVERAGE",
},
{
"answer": "SUM > 36542, 4512, 3934",
"coordinates": [(0, 1), (1, 1), (2, 1)],
"cells": ["36542", "4512", "3934"],
"aggr... | Python | 1 |
ap()
});
});
}
group.finish();
}
fn random_update(c: &mut Criterion) {
let mut group = c.benchmark_group("morton table random_update");
for size in 8..13 {
let size = 1 << size;
group.bench_with_input(BenchmarkId::from_parameter(size), &size, |b, &size| {
... | Rust | 0 |
:returns: WithdrawSolver -- Ethereum withdraw solver instance.
>>> from swap.providers.ethereum.solver import WithdrawSolver
>>> recipient_root_xprivate_key: str = "xprv9s21ZrQH143K3XihXQBN8Uar2WBtrjSzK2oRDEGQ25pA2kKAADoQXaiiVXht163ZTrdtTXfM4GqNRE9gWQHky25BpvBQuuhNCM3SKwWTPNJ"
>>> withdraw_solver: Withd... | Python | 1 |
# similarity_DP.py
import json
import torch
from sentence_transformers import SentenceTransformer, util
from tqdm import tqdm
import nltk
from konlpy.tag import Okt
import numpy as np
import re
import pandas as pd
# Ensure you have the necessary NLTK data files
nltk.download('punkt')
# Manually defined list of Korea... | Python | 1 |
date: Option<String>
}
#[derive(Serialize, Debug)]
pub struct Episode {
title: String,
url: String,
description: String,
file_url: String,
published_date: String,
duration: u32,
length: u32
}
fn main() {
rocket::ignite()
.mount("/", routes![router::podcast_by_user_name,
... | Rust | 0 |
import os
import numpy as np
import json
import cv2
import sys
import sys
base_dir = os.getcwd()
sys.path[0] = base_dir
DATA_PATH = r'/work/RsCarData'
OUT_PATH = os.path.join(DATA_PATH, 'annotations')
if not os.path.exists(OUT_PATH):
os.makedirs(OUT_PATH)
SPLITS = ['train', 'val']
for split in SPLITS:
data... | Python | 1 |
test!(
google_fonts_url,
"a {\n color: url(http://fonts.googleapis.com/css?family=Karla:400,700,400italic|Anonymous+Pro:400,700,400italic);\n}\n",
"a {\n color: url(http://fonts.googleapis.com/css?family=Karla:400,700,400italic|Anonymous+Pro:400,700,400italic);\n}\n"
);
test!(
interpolation_in_http_ur... | Rust | 0 |
personalization: u8,
transcript_digest: &[u8]) -> G2
{
let g1_s_enc = bincode::encode(&g1_s, INF)
.expect("g1_s encoding");
let g1_s_x_enc = bincode::encode(&g1_s_x, INF)
.expect("g1_s_x encoding");
// Compute BLAKE2b(personalization | transcript | g^s | g^{s*x})
let mut h = Bla... | Rust | 0 |
Error code
":: cty :: c_int" => {
// Return Int
if returns_int { quote! { Ok(res) } }
// Return Error Code
else {
quote! {
match res {
0 => Ok(()),
... | Rust | 0 |
Type::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn fnstcw_1() {
run_test(&Instruction { mnemonic: Mnemonic::FNSTCW, operand1: Some(IndirectScaledIndexedDisplaced(BX, SI, One, 32360, Some(OperandSize::Word), None)), operand2: None, operand3: None, ... | Rust | 0 |
h,
limits::{SEQUENCE_LOCKTIME_DISABLE_FLAG, SEQUENCE_LOCKTIME_TYPE_FLAG},
},
policy::concrete::Policy,
Descriptor, ForEachKey, MiniscriptKey, Segwitv0, Terminal, TranslatePk2,
};
use std::{
fmt::{self, Display},
str::FromStr,
};
#[cfg(feature = "use-serde")]
use serde::de;
/// Flag applie... | Rust | 0 |
from typing import Dict, Any, List
from utils.functions import generate_id
class Schedule:
def __init__(self, class_id: int, day: str):
self.id = generate_id()
self.class_id = class_id
self.day = day
self.lessons: Dict[str, Dict[str, Any]] = {}
def add_lesson(self, time: str, s... | Python | 1 |
# R.Gacesa (UMCG, 2022)
# ========================================================
# cleans contig names for downstream binning compatibility
# =========================================================
# > uses BioPython for loading FASTA
# > uses argparse for parsing sys input
# === MAIN ===
from Bio import SeqIO
imp... | Python | 1 |
from benchopt import BaseDataset, safe_import_context
with safe_import_context() as import_ctx:
import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import LabelEncoder
from skada.utils import source_target_merge
from skada.datasets import fetch_office_home_all
# Al... | Python | 1 |
# Copyright 2024 Canonical Ltd.
# Authors:
# - Hector Cao <hector.cao@canonical.com>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that... | Python | 1 |
from multiprocessing import Pool
import os
import sys
import numpy as np
def num_list(time):
n = len(time)//unit_
r = len(time)%unit_
return [unit_ for _ in range(n)] + [r]
width = int(sys.argv[1]) #시뮬레이션 공간의 가로길이
height = int(sys.argv[2]) #시뮬레이션 공간의 세로길이
time_cut = int(sys.argv[3]) #시뮬레이션 시간길이
num = int(... | Python | 1 |
checked_add(1).ok_or(ArithmeticError::Overflow)?;
NFTsOwned::<T>::try_append(&owner, nft.id).map_err(|()| Error::<T>::TooManyOwned)?;
NFTs::<T>::insert(nft.id, nft);
NFTCnt::<T>::put(new_cnt);
// Emit an event.
Self::deposit_event(Event::Created{ nft: hash, owner });
// Return a successful Dispatch... | Rust | 0 |
media = 0
cont = 0
nt = float(input('Digite a nota: '))
while nt >= 0:
| Python | 1 |
ma_cuda = False
try:
import torch
has_torch_cuda = torch.cuda.is_available()
except:
pass
try:
import llama_cpp
has_llama_cuda = any('cuda' in attr.lower() or 'gpu' in attr.lower() for attr in dir(llama_cpp.Llama))
except:
pass
print(f"NVIDIA drivers detected: {has_nvidia_drivers}")
print(f"C... | Python | 1 |
elif self.__account.get_currency_rates(symbol)["mc"] == "SEK":
return max(min_sek, qty * price * eu_asia_cm)
else:
return max(min_com, qty * price * eu_asia_cm)
def _estimate_forex_commission(self, lot):
return 3.0 * lot
def _estimate_commodity_commiss... | Python | 1 |
script specifies the application name,
# decides which components/values to use for what feature,
# and creates an instance of Bar to work with
#
if __name__ == '__main__':
print '\n*** IoC Demo ***'
features.Provide('AppTitle', 'Inversion of Control ...\n\n... The Python Way')
features.Provide('CurrentUser', ... | Python | 1 |
x[i] = np.transpose(
np.fliplr(np.transpose(x[i], (0, 2, 1))), (0, 2, 1))
# x = x.swapaxes(dim, 0)
# x = x[::-1, ...]
# x = x.swapaxes(0, dim)
return torch.from_numpy(x.copy())
def shuffleLR(x, dataset):
flipRef = dataset.flipRef
assert (x.dim() == 3 or x.dim() == 4... | Python | 1 |
# .py
#大华智能物联综合管理平台 任意文件读取漏洞复现(QVD-2023-45063)
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from requests.exceptions import Timeout
import os
import urllib.parse
import urllib.request
def sc_send(text, desp='', key='[SENDKEY]'):
postdata = urllib.parse.urlencode({'text': ... | Python | 1 |
)
}
/// Read the FTDIChip-ID from R-type devices
/// ftdi_context should be initialized previously
/// return FTDIChip-ID value
pub fn ftdi_read_chipid(&self) -> Result<u16> {
debug!("start \'ftdi_read_chipid\' ...");
self.check_usb_device()?;
let mut a: c_uchar = 0 as c_uch... | Rust | 0 |
ncoded::to_string(&query_args).unwrap();
let url = format!("/oauth.v2.access?{}", query_);
self.client.get(&url, None).await
}
}
pub use warp_websockify::WebsockifyError;
use clap::{crate_authors, crate_version, App, Arg};
use log::info;
use rust_embed::RustEmbed;
use std::env;
use std::net::ToSoc... | Rust | 0 |
igin_process: Option<OriginProcess>,
state: State,
date: Moment,
) -> Self {
Self {
id ,
remaining_amount: amount.clone(),
amount,
origin_process,
state,
date,
}
}
pub fn subtract_amount(mut se... | Rust | 0 |
.sig.output = parse_quote!(
->
impl
#minimum_lifetime +
::fix_hidden_lifetime_bug::core::future::Future<
Output = #Ret,
>
);
// 4) In the to-be-generated `async move { … }` function body, we need to
// make sure all the function parameters... | Rust | 0 |
wrap());
}
#[test]
fn build_cbmt_proof() {
let leaves = vec![2i32, 3, 5, 7, 11, 13];
let leaf_index = 5u32;
let proof_leaf = leaves[leaf_index as usize].clone();
let proof = CBMTI32::build_merkle_proof(&leaves, &leaf_index).unwrap();
assert_eq!(vec![11, 2, 1], proo... | Rust | 0 |
a: MappedVma,
heap_vma: LazilyMappedVma,
vmctx_container: VmContextContainer,
) {
*self.heap.write() = heap_vma;
*self.static_wasm_data.lock() = Some(StaticWasmThreadData {
code: code_vma,
_vmctx_container: vmctx_container,
});
}
/// Gets the ... | Rust | 0 |
from odoo import models
class PosOrder(models.Model):
_inherit = 'pos.order'
def get_l10n_es_pos_tbai_qrurl(self):
""" This function manually triggers the account.edi post CRON and synchronously
wait for the process to finish, so that we can retrieve the generated QR code
from the pos... | Python | 1 |
'befik': '11(b9,b13)(omit5)',
'bfhik': '11(b9,b13)(omit3)',
'bfik': '11(b9,b13)(omit3,5)',
'befhi': '(b9,11,b13)',
'bdfhi': 'm(b9,11,b13)',
'defhik': '11(#9,b13)',
'defik': '11(#9,b13)(omit5)',
'befi': '(b9,11,b13)(omit5)',
'bfhi': '5(b9,11,b13)',
'bdfi:': 'm(b9,11,b13)(omit5)',
... | Python | 1 |
_object(UserRef::new(response_address), &response)
}
virtio_magma_ctrl_type_VIRTIO_MAGMA_CMD_VIRT_CREATE_IMAGE => {
let (control, mut response): (
virtio_magma_virt_create_image_ctrl_t,
virtio_magma_virt_create_image_resp_t,
... | Rust | 0 |
());
}
#[test]
fn test_mangle_lists() {
const ENCRYPTION_KEY: &str = "<KEY>";
let secret_list = email_encryption::encrypt(ENCRYPTION_KEY, "<EMAIL>")
.expect("failed to encrypt list");
let secret_member = email_encryption::encrypt(ENCRYPTION_KEY, "<EMAIL>")
.... | Rust | 0 |
# -*- coding: utf-8 -*-
#
# This file is part of EventGhost.
# Copyright © 2005-2020 EventGhost Project <http://www.eventghost.net/>
#
# EventGhost is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either versio... | Python | 1 |
w: self }
}
#[doc = "Bit 13"]
#[inline]
pub fn syson_pmopt_slp_syspll_en(&mut self) -> _SYSON_PMOPT_SLP_SYSPLL_ENW {
_SYSON_PMOPT_SLP_SYSPLL_ENW { w: self }
}
#[doc = "Bit 12"]
#[inline]
pub fn syson_pmopt_slp_xtal_en(&mut self) -> _SYSON_PMOPT_SLP_XTAL_ENW {
_SYSON_PMOPT... | Rust | 0 |
== 0: return None
if P1 != P2:
m = ((y2 - y1) * _inv((x2 - x1) % P)) % P
else:
m = ((3*x1*x1) * _inv((2*y1) % P)) % P
x3 = (m*m - x1 - x2) % P
y3 = (m*(x1 - x3) - y1) % P
return (x3, y3)
def _point_mul(k, P0):
R = None
addend = P0
while k:
if k & 1: R = _point_add... | Python | 1 |
is_disabled(&self) -> bool {
*self == CH0LIMITH_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == CH0LIMITH_A::ENABLED
}
}
#[doc = "Write proxy for field `CH0LIMITH`"]
pub struct CH0LIMITH_W<'a> {
... | Rust | 0 |
) -> Pin<Box<dyn Future<Output = Result<JsValueFacade, JsError>>>>;
/// eval a script, please note that eval should not be used for production code, you should always
/// use modules or functions and invoke them
/// eval will always need to parse script and some engines like StarLight even require a diffe... | Rust | 0 |
tch.group(1))
# Parse turn
turn_match = self.patterns['turn'].search(text)
if turn_match:
hand.turn = turn_match.group(1).strip()
# Parse river
river_match = self.patterns['river'].search(text)
if river_match:
hand.river = river_m... | Python | 1 |
}
}
panic!("Here be dragons");
}
/// Returns a `BTreeMap`. The key is of type u32.
/// (`f32` is not `Ord`, hence we can't use it as key.) You can optionally specify a
/// scale function, e.g. multiply all frequencies with 1000 for better
/// accuracy when represented ... | Rust | 0 |
have not tested this in production
let uri = req.get_uri().unwrap();
assert_eq!(
uri.to_string(),
"https://api.twitch.tv/helix/users/blocks?target_user_id=41245071"
);
dbg!(BlockUserRequest::parse_response(Some(req), &uri, http_response).unwrap());
}
<reponame>TDHolmes/oven-temp-rs<fi... | Rust | 0 |
se::get().unwrap_or_default();
let event = EventRecord {
phase,
event,
topics: topics.iter().cloned().collect::<Vec<_>>(),
};
// Index of the to be added event.
let event_idx = {
let old_event_count = EventCount::get();
let new_event_count = match old_event_count.checked_add(1) {
// We've re... | Rust | 0 |
hmark = False
# possibly at the cost of reduced performance
# (the algorithm itself may be nondeterministic).
# Causes cuDNN to use a deterministic convolution algorithm,
torch.backends.cudnn.deterministic = True
# but may slow down performance.
# ... | Python | 1 |
):
# We will restrict access to the /admin/ path
if request.path.startswith('/admin/'):
if not request.user.is_authenticated:
return HttpResponseForbidden("Access Denied: Authentication required.")
# Check if user has a 'role' attribute and if it is '... | Python | 1 |
::default()
})
}
_ => None,
};
#[cfg(unix)]
if let Some(info) = import_fd_info.as_mut() {
allocate_info = allocate_info.push_next(info);
}
let mut allocation_count = device.allocation_count().lock().expect("Poisoned mutex");
... | Rust | 0 |
p=float(input('enter the principle: '))
t=float(input('enter the time:(in months) '))
r=float(input('enter the rate of interest: '))
sI=(p*t*r)/100.0
print('simple interest= ',sI)
compoundI=p*pow((1+r/100),t)
print('Amount= ',p+sI)
print('compound interest = ', compoundI)
| Python | 1 |
{
Some(addr) => Ok(addr.ip().to_string()),
None => Err(Error::HostNotFound(host.to_string())),
}
}
#[test]
fn resolve_works() {
assert!(resolve(".").is_ok());
assert!(resolve("localhost").is_ok());
assert!(resolve(&std::env::var("COMPUTERNAME").unwrap()).is_ok());
}
pub fn replace_par... | Rust | 0 |
crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sensitive_internal_sram_usage_3](sensitive_internal_sram_usage_3) module"]
pub type SENSITIVE_INTERNAL_SRAM_USAGE_3 = crate::Reg<u32, _SENSITIVE_INTERNAL_SRAM_USAGE_3>;
#[allow(miss... | Rust | 0 |
, Copy, Clone)]
pub enum LogLevel {
/// A level lower than all log levels.
Off,
/// Corresponds to the `Error` log level.
Error,
/// Corresponds to the `Warn` log level.
Warn,
/// Corresponds to the `Info` log level.
Info,
/// Corresponds to the `Debug` log level.
Debug,
/// ... | Rust | 0 |
is not None:
#rotate data to (estimated) world frame (iDynTree floating base wants that)
#TODO: use quaternions to avoid gimbal lock (orientation estimation needs to give quaternions already)
IMUlinAccWorld = np.zeros_like(IMUlinAcc)
IMUrotVelWorld = np.z... | Python | 1 |
.map(Clone::clone)
.collect::<Vec<K>>()
})
.unwrap_or(vec![])
})
.collect();
buckets.into_iter()
}
pub fn values<'table>(&'table self) -> impl Iterator<Item = V> + 'table {
let buckets: Vec<V> = self
... | Rust | 0 |
;
use std::path::{Path, PathBuf};
use serde_derive::{Deserialize, Serialize};
use crate::other;
#[derive(Serialize, Deserialize, Debug, Default)]
#[serde(default)]
pub struct Config {
pub local_addr: String,
pub remote_addr: String,
pub domain_name: String,
pub ca_certificate: String,
pub server_... | Rust | 0 |
# -*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class HrPayslipInput(models.Model):
_name = 'hr.payslip.input'
_description = 'Payslip Input'
_order = 'payslip_id, sequence'
name = fields.Char(string="Description")
... | Python | 1 |
, non_upper_case_globals)]
use crate::t_eprint;
use std::ptr;
use crate::help;
use crate::node::Picture;
use crate::xetex_errors::error;
use crate::xetex_ini::{cur_list, input_state_t};
use crate::xetex_scaledmath::Scaled;
use crate::xetex_xetex0::{scan_decimal, scan_dimen, scan_file_name, scan_int, scan_keyword};
us... | Rust | 0 |
t rect = Rectangle {
width: 7u8,
height: 23u8,
};
println!("rect is {:?}", rect);
let rect = Shape {
width: 456u16,
height: 78.54f32,
};
println!("rect is {:?}", rect);
println!("rect width is {:?}", rect.get_width());
let rect = Shape {
width: 54u... | Rust | 0 |
rite!(f, "{}", "all"),
EnabledRepositories::NONE => write!(f, "{}", "none"),
EnabledRepositories::SELECTED => write!(f, "{}", "selected"),
}
}
}
impl std::str::FromStr for EnabledRepositories {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s ... | Rust | 0 |
end(WAIT_CHAIN.into(), &Default::default(), &[]);
// let mut clients_started = 0;
// while clients_started < args.total_handles {
// log.snapshot(WAIT_CHAIN.into());
// while let Ok(..) = log.get_next() {
// clients_started += 1
// }
// }
STARTED.store(true, Ordering:... | Rust | 0 |
ASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `RX_IRQ_EN`"]
pub enum RX_IRQ_ENW {
#[doc = "RX Interrupt is not enabled."]
_0,
#[doc = "RX Interrupt is enabled."]
_1,
}
impl RX_IRQ_ENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub ... | Rust | 0 |
te['qfmt'] != template['qfmt']:
existingTemplate['qfmt'] = template['qfmt']
if existingTemplate['afmt'] != template['afmt']:
existingTemplate['afmt'] = template['afmt']
else:
existingModel: NotetypeDict = mm.new(modelName)
for fieldName in fie... | Python | 1 |
from collections import deque
from typing import List
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
start = "0000"
deadends = set(deadends)
if start in deadends:
return -1
queue = deque([(start, 0)])
visited = set()
visite... | Python | 1 |
ra), cluster_index, filename_string, line.rstrip(), parent_mass)
cluster_node.user_group = user_group_string
cluster_node.default_group = default_group_string
#Parsing component index
if(component_index != -1):
cluster_node.componentindex = int(splits[com... | Python | 1 |
d_certificate_1)
.await
.unwrap();
// Wait for the certificate to be processed.
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
// Ensure the last consensus index is correctly updated.
assert_eq!(
state.db().last_consensus_index().unwrap(),
SequenceNumb... | Rust | 0 |
set_bit(i, false);
}
}
<gh_stars>1-10
use crate::map::Map;
use std::collections::HashMap;
// Reference: https://www.redblobgames.com/pathfinding/a-star/implementation.html
pub fn breadth_first(map: &Map, from: (usize, usize), to: (usize, usize)) -> Vec<(usize, usize)> {
// The cells that still need to be proce... | Rust | 0 |
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
# import necessary libarities
import pandas as pd
from sklearn import tree
from sklearn.preprocessing import LabelEncoder
from sklearn.naive_bayes import GaussianNB
# load data from CSV
data = pd.read_csv('tennisdata.csv')
print("THe first 5 values of data is :\n",data.head())
# obtain Train data and Train output
X =... | Python | 1 |
gap score. By default at -8.",
default=-8.0,
)
parser.add_argument(
"--protein_sequence",
help="Inform if the sequence type are a protein sequence or a nucleic acids sequence. Set by default at True",
default=True,
action="store_false",
)
return parser.parse_arg... | Python | 1 |
count(')')
iter += 1
# join with comma and remove leading and trailing spaces.
# also remove backslashes as some people like to add them before newlines...
i = ','.join(lines[begin:iter]).strip().replace('\\', '')
# The first (possibly only) word in i is the enum element name.
m = enum_ele... | Python | 1 |
"""
Circular Hough Transform Peak Finding
=====================================
The Circular Hough Transform is a method to detect circular features in an image. It can be
used to detect rings (or disks) in the diffraction pattern. For strain mapping there is
some evidence that the Circular Hough transform is more ac... | Python | 1 |
n resource_id="orchestrator_config",\n details={\n 'old_config': old_config,\n 'new_config': new_config,\n 'updated_keys': list(new_config.keys())\n }\n )\n \n ... | Python | 1 |
# Correct endpoint
json=message_payload,
headers={"Authorization": f"Bearer {employee_token}"},
)
assert message_response.status_code == 200
assert message_response.json()["content"] == "Thank you for your answer."
# 8. Admin completes the in... | Python | 1 |
, buf } = Pin::into_inner(self);
try_io!(socket.try_peek_from(&mut *buf))
}
}
/// The [`Future`] behind [`UdpSocket::peek_from_vectored`].
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct PeekFromVectored<'a, B> {
socket: &'a mut UdpSocket<Unconnected>,
... | Rust | 0 |
if n == 1:
reactant_smiles_dict[reactant_name].append(each_smi)
return reactant_smiles_dict
def create_building_blocks(self):
print('start to collect smiles:')
collected_smiles_list = self._load_filter_building_blocks()
print('sort smiles by reacta... | Python | 1 |
#!/usr/bin/env python3
"""
麦咪的数字占卜脚本 🔮
每小时为项目带来新的运势喵~
"""
import datetime
import hashlib
import random
def get_seed():
"""基于当前小时生成种子,确保同一小时内结果一致 (使用UTC+8时区)"""
# 使用UTC时间加8小时得到北京时间
now = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
# 使用年月日小时作为种子,确保每小时更新
seed_str = f"{now.year}{now.mo... | Python | 1 |
from __future__ import annotations
from mteb.abstasks.TaskMetadata import TaskMetadata
from ....abstasks.AbsTaskRetrieval import AbsTaskRetrieval
class RARbMath(AbsTaskRetrieval):
metadata = TaskMetadata(
name="RARbMath",
description="Measuring the ability to retrieve the groundtruth answers to ... | Python | 1 |
point = (node.lon(), node.lat());
nodes.insert(node.id, point);
let tags = node.tags().into_iter().collect();
let encoded = encode::node(node.id as u64, point, tags).unwrap();
println!("{}", hex::encode(encoded));
}
... | Rust | 0 |
method = 'SimVP'
# model
spatio_kernel_enc = 3
spatio_kernel_dec = 3
# model_type = None # define `model_type` in args
hid_S = 64
hid_T = 512
N_T = 8
N_S = 4
# training
lr = 1e-3
batch_size = 16
sched = 'cosine'
warmup_epoch = 0 | Python | 1 |
s_ref(), Some(prefix), is_pub)
}
UseTree::Glob(_) => {
let path = prefix.expect("Glob pattern should have a path prefix");
if let Ok(Some(module)) = self.target().module_by_use_path(path.as_str()) {
module.pub_uses().iter().cloned().cloned().co... | Rust | 0 |
#[test]
fn test_substitute_parameters() {
let mut circs: Vec<Circuit> = Vec::new();
let mut circ1 = Circuit::new();
let mut circ1_subs = Circuit::new();
circ1 += operations::RotateX::new(0, "theta".into());
circ1_subs += operations::RotateX::new(0, 0.0.into());
let mut circ2 = Circuit::new();
... | Rust | 0 |
Set::new(vec![Ed25519Public::default(), Ed25519Public::default()], 1),
)])
.unwrap(),
governors_signature: None,
block_version: BlockVersion::ONE,
}
.into();
let responder_id1 = ResponderId("1.2.3.4:5".to_string());
assert_ne!(
... | Rust | 0 |
e = cell.as_ref().into();
model.set_value(&iter, column as u32 + 1, &value);
}
}
self.spreadsheet_view.set_model(Some(&model));
}
}
Ok(())
}
fn on_edit(&self, _: &CellRendererText, column: i64, path: TreeP... | Rust | 0 |
abs() >= w
}
// Otherwise u - v = w exactly, or w is not the smallest value. In either
// case the following returns the correct result.
if u >= v {
return u-w >= v
}
v-w >= u
}
// exitAxis reports which axis the directed line L exits the cube face F... | Rust | 0 |
# SPDX-FileCopyrightText: Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Filter for QtWebEngine cookies."""
from qutebrowser.config import config
from qutebrowser.utils import utils, log
from qutebrowser.misc import objects
@utils.prevent_exceptions(False) # R... | Python | 1 |
from library_system import Book, EBook, PrintBook, Library
def main():
# Create a Library instance
my_library = Library()
# Create instances of each type of book
classic_book = Book("Pride and Prejudice", "Jane Austen")
digital_novel = EBook("Snow Crash", "Neal Stephenson", 500)
paper_novel = ... | Python | 1 |
m/src/orc.rs
//! Module for generating ORC Module.
pub struct ORCJIT {
}
use crate::abstracts::{
AbstractBoundary,
AbstractBoundaryCollection,
AbstractNode,
AbstractNodeQueue,
AbstractAttacherCollection,
AbstractAttacherNode
};
use super::ScopeStack;
impl<T, U, V, W, X, Y> ScopeStack<T, U, V, W, X, Y>
where
T:... | Rust | 0 |
#file: backend/app/domain/mappers/movimiento_mapper.py
from app.domain.models.movimiento import Movimiento, TipoMovimiento as DomainTipoMovimiento
from app.db.models.movimiento import MovimientoORM
def movimiento_orm_to_domain(orm: MovimientoORM) -> Movimiento:
return Movimiento(
id=orm.id,
product... | Python | 1 |
pMapListDataset {
data4: BTreeMap::new(),
data6: BTreeMap::new(),
};
}
pub fn insert(&mut self, ip: SiemIp, data: Vec<Cow<'static, str>>) {
match ip {
SiemIp::V4(ip) => {
self.data4.insert(ip, data);
}
SiemIp::V6(ip) => ... | Rust | 0 |
# Add the seed criteria to the fingerprint
self.fingerprint[seed_criteria[0]] += (self.seed_criteria[seed_criteria[0]],)
# Get the extra user requested csv data
for column in PEATSAorder.extra_csv_column_definitions:
# This does not need to succ... | Python | 1 |
if initialize is not False:
init_weights(self.modules, initialize)
def forward(self, x, label, evaluation=False):
with torch.cuda.amp.autocast() if self.mixed_precision is True and evaluation is False else dummy_context_mgr() as mp:
h = x
for index, blocklist i... | Python | 1 |
# Dictionary for Morse code
morse_code = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-",
... | Python | 1 |
"""
Function: Spike train distance curves : polarity inference measurement, polarity independent measurement and Hamming distances.
Author: Jianing Li, lijianing@pku.edu.cn, Peking University, Oct. 29th, 2018.
"""
import numpy as np
from matplotlib import pyplot as pl
from scipy.interpolate import spline
from event_p... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.