text string | label_name string | labels int64 |
|---|---|---|
import numpy as np
from .. import algebra
from numba import jit
@jit(nopython=True)
def maximum_wannier_gap(m):
"""Return the maximum wannier gap"""
x = m[0]
# find the position of the maximum gap at every t
fermis = x*0. # maximum gap
for it in range(len(x)): # loop over times
dmax = -1 # ... | Python | 1 |
try:
task_id, task = next(task_iter)
except StopIteration:
log("[INFO] Todas as tasks foram avaliadas.")
break
task_start = time.time()
input_grid = task["train"][0]["input"]
log(f"[INFO] Avaliando task {task_id} ({total_tasks + 1})")
result = conversational_loop(models, ... | Python | 1 |
import os, base64, uuid
from django.conf import settings
from datetime import datetime
import algo
# Encrypt a file using AES, 3DES, and RC2
def EncryptFile(FilePath):
with open(FilePath, 'rb') as F:
FileData = F.read()
# Split the file into 3 parts
PartSize = len(FileData) // 3
Part1, Part2,... | Python | 1 |
word: for")?,
Token::If => write!(f, "Keyword: if")?,
Token::Inline => write!(f, "Keyword: inline")?,
Token::Goto => write!(f, "Keyword: goto")?,
Token::Float => write!(f, "Keyword: float")?,
Token::Int => write!(f, "Keyword: int")?,
Token::Long =>... | Rust | 0 |
/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A Big integer (signed version: `BigInt`, unsigned version: `BigUint`).
//!
//! A `BigUint` is represented as a vector of `BigDigit`s.
//! A `BigInt` is a combination of `BigUint` and `Sign`.... | Rust | 0 |
they appear in order 0..n
, b"w:num" => {
num_id_opt = Some(attr_as_usize(e,b"w:numId"));
}
, _ => ()
}
}
, Ok(Event::Empty(ref e)) => {
match e.name() {
b"w... | Rust | 0 |
# imports
import pandas as pd
import numpy as np
import fileIntegrity
import patientSelection
from sleepSchedule import getSleepVariance
from roomUsage import getRoomUsageMetric
from sleepQuality import getSleepQuality
# define
plot = False
# filePaths
activityPath = 'TIHM_Dataset/Activity.csv'
sleepPath = 'TIHM_Dat... | Python | 1 |
k,
k - 1,
k - 2,
k - 1,
k - 2
)
}),
&b_k_minus_1_plus_b_k_minus_2,
&a_k_minus_1_plus_a_k_minus_2,
)?;
b_k_minus_1_plus... | Rust | 0 |
from chatterbot.logic import LogicAdapter
from chatterbot.conversation import Statement
from chatterbot import languages
from chatterbot.utils import get_model_for_language
import spacy
class SpecificResponseAdapter(LogicAdapter):
"""
Return a specific response to a specific input.
:kwargs:
* *in... | Python | 1 |
::<error::Unspecified>();
test::compile_time_assert_std_error_error::<error::KeyRejected>();
}
<gh_stars>1-10
#[derive(Copy, Clone)]
pub enum Mode {
Text,
Fg,
Bg,
Style,
}
<filename>gateway/src/main.rs
mod events;
mod modules;
mod links;
mod bucket;
use std::sync::Arc;
use crate::events::on_event;
... | Rust | 0 |
from pdf completed : {len(pdf_elements)}")
# Separate images and tables
images, img_elements, tables, table_elements = reload_pickle(
"categorized_elements.pkl", elements_wise_extractor, pdf_elements, "Image", "Table"
)
logging.info(f"Categorized : Images={len(images)} , image_Elements={len(im... | Python | 1 |
EventId,
sampled_profile: RustSampledProfile,
device_os_name: String,
device_os_version: String,
version_name: String,
version_code: String,
debug_meta: RustDebugMeta,
}
pub fn parse_rust_profile(item: &mut Item) -> Result<(), ProfileError> {
let profile: RustProfile =
serde_json::... | Rust | 0 |
import pandas as pd
from collections import defaultdict
OFF_COLS = ["avg","obp","slg","woba","wrc_plus","war","k_pct","bb_pct"]
DEF_COLS = ["k_per_9","bb_per_9","hr_per_9","era","fip","owar"]
def blend_stats(game_stats, projection_stats, c_off=60, c_def=40):
a, b = game_stats.index
game_id = game_stats.a... | Python | 1 |
.ok()
.map(|v| (v * 1000000.0 + 0.5) as u64);
}
}
None
}
}
*/
fn cpu_model() -> Option<String> {
if let Ok(content) = fs::read_to_string("/proc/cpuinfo") {
for line in content.lines() {
if line.starts_with("model name\t") {
le... | Rust | 0 |
d operated by the context.
///
/// Generally used when the context is a Elexeum Relay-chain.
Parachain(#[codec(compact)] u32),
/// A 32-byte identifier for an account of a specific network that is respected as a sovereign endpoint within
/// the context.
///
/// Generally used when the context is a Substrate-bas... | Rust | 0 |
::Option<Affinity> {
match value {
0 => ::std::option::Option::Some(Affinity::AF_Unparsed),
1 => ::std::option::Option::Some(Affinity::Friend),
2 => ::std::option::Option::Some(Affinity::Foe),
3 => ::std::option::Option::Some(Affinity::Unknown),
_ => :... | Rust | 0 |
import os
from itertools import chain
from typing import Dict, List
try:
import regex as re
except ImportError:
import re
from pathlib import Path
from collections import defaultdict
from dataclasses import dataclass
from numbers import Number
from lumo.exp import Experiment, finder
match_metric_v0 = re.comp... | Python | 1 |
import numpy as np
# --- PL-DATAMODULE ---
def get_local_split(items: list, world_size: int, rank: int, seed: int):
""" The local rank only loads a split of the dataset. """
n_items = len(items)
items_permute = np.random.RandomState(seed).permutation(items)
if n_items % world_size == 0:
padde... | Python | 1 |
equest = Request::builder(
Method::PUT,
"http://localhost/store/person/2.ttl".parse().unwrap(),
)
.with_header(HeaderName::CONTENT_TYPE, "text/turtle; charset=utf-8")
.unwrap()
.with_body(
"
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix v: <http... | Rust | 0 |
);
self
}
/// Apply the background color bright magenta value to the escape
/// sequence.
pub fn bg_bright_magenta(&mut self) -> &mut Self {
self.values.push(BG_BRIGHT_MAGENTA);
self
}
/// Apply the background color bright cyan value to the escape
/// sequence.
... | Rust | 0 |
oling = e2_layers.average_pooling_Rn
def forward(self, x):
# 'ConvBlock'
h = self.conv(torch.relu(self.bn(x)))
# AvgPooling
h = self.pooling(h, kernel_size=2, stride=2, padding=0)
return h
if __name__ == '__main__':
from experiments.utils import num_params
model = ... | Python | 1 |
#!/usr/bin/env python3
"""
Debug collision rectangle calculations
"""
import sys
import os
# Add the current directory to the path so we can import the game module
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from frog_platformer import Platform, PlatformType, Frog
from pygame import Rect
def deb... | Python | 1 |
"""
This file may have been modified by Bytedance Ltd. and/or its affiliates (“Bytedance's Modifications”).
All Bytedance's Modifications are Copyright (year) Bytedance Ltd. and/or its affiliates.
Reference: https://github.com/MendelXu/SAN/blob/main/san/data/datasets/register_coco_stuff_164k.py
"""
import os
from d... | Python | 1 |
== 0 {
state.animation_state.advance();
}
}
fn is_hard(&self) -> bool {
true
}
fn is_enterable(&self) -> bool {
true
}
fn is_collectible(&self) -> bool {
true
}
fn render(&self, renderer: &mut Canvas<Window>, transform: &TransformContext, ... | Rust | 0 |
e/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
# 'referer': 'https://news.jinhua.com.cn/?pp=12',
})
params = (
('pp', str(12 * (page_num - 1))), # 格式为: '0', '12', '24'
)
body = Requests.get_url_body(
url='https://news.jinhua.com.cn/',
... | Python | 1 |
"color: red; font-size: 10px;")
label_2.setWordWrap(True)
vbox.addWidget(label_2)
return widget
def _build_skill_icon(self, skill: SpawnSkill, job_id) -> QFrame:
frame = QFrame()
icon = build_icon(skill.icon, skill.id, 25, frame)
icon.move(9, 9)
frame.setFixe... | Python | 1 |
use crossbeam_channel::{self as channel, Receiver, Sender};
use indexmap::IndexMap;
use lazy_static::lazy_static;
use log::*;
use parking_lot::RwLock;
use std::{
fs,
io::{self, BufRead, Write},
sync::{
atomic::{AtomicBool, Ordering::SeqCst},
Arc,
},
};
pub type FxIndexMap<K, V> = Index... | Rust | 0 |
"""Generate dhcp file."""
from __future__ import annotations
from .model import Config, Integration
from .serializer import format_python_namespace
def generate_and_validate(integrations: dict[str, Integration]) -> str:
"""Validate and generate dhcp data."""
match_list = []
for domain in sorted(integrat... | Python | 1 |
) -> InternalResult<impl Stream<Item = InternalResult<Vec<String>>> + 'a> {
let dirs = fs::read_dir(&self.root)
.await
.context(UnableToListDirectory { path: &self.root })?;
let s = dirs
.context(UnableToProcessEntry)
.and_then(|entry| {
... | Rust | 0 |
rbf_node.connectRBFToggleAttr(
drivenControlName, self.name, self.getRBFToggleAttr()
)
return attrs_dict
def copyPoses(self, nodeB):
poseInfo = self.getDriverControlPoseAttr()
nodeB.setDriverControlPoseAttr(poseInfo)
copyPoses(self.name, nodeB)
def... | Python | 1 |
import random
import string
import spade
from spade.agent import Agent
from spade.behaviour import CyclicBehaviour
from spade.message import Message
from spade.template import Template
class Sender(Agent):
class CommsBehaviour(CyclicBehaviour):
async def on_start(self):
print("[" + str(self.a... | Python | 1 |
= vec![vec![1, 2], vec![3, 4], vec![5, 6], vec![7, 8], vec![9, 10]];
let uint32_builder = arrow::array::UInt32Builder::new(vals.len());
let mut uint32_list_builder =
arrow::array::FixedSizeListBuilder::new(uint32_builder, vals[0].len() as i32);
for list in &vals {
for nu... | Rust | 0 |
;
}
/// Run a shell command. Panic if it fails in any way.
fn cmd(cmd: &str, args: &[&str]) {
let ecode = Command::new("ip")
.args(args)
.spawn()
.unwrap()
.wait()
.unwrap();
assert!(ecode.success(), "Failed to execte {}", cmd);
}
fn main() {
// let cfg = Config {
// ... | Rust | 0 |
_raw(raw)?;
Ok(tx.into())
}
/// Hashes for the service tables that will be included into the state hash.
/// To simplify things, we don't have [Merkelized tables][merkle] in the service storage
fn state_hash(&self, _: &Snapshot) -> Vec<Hash> {
vec![]
}
/// Create a REST `Handle... | Rust | 0 |
ning")
# parser.add_argument('--max_epochs', type=int, default=10, help="Number of training epochs")
# args = parser.parse_args()
# # DataModule
# data_module = EmbeddingDataModule(args.metadata_csv, args.embeddings_dir, args.batch_size)
# # Model
# model = LinearProbe(args.input_dim, args.num... | Python | 1 |
import string
import djvu.decode
import pytest
from .text import TextExtractVisitor
def remove_whitespace(src: str):
return src.translate({ord(c): None for c in string.whitespace})
def test_extract_djvu_page_text_words():
document = djvu.decode.Context().new_document(
djvu.decode.FileURI('fixtures... | Python | 1 |
= "GDK_KEY_kana_RA")]
pub const kana_RA: Key = Key(ffi::GDK_KEY_kana_RA as u32);
#[doc(alias = "GDK_KEY_kana_RE")]
pub const kana_RE: Key = Key(ffi::GDK_KEY_kana_RE as u32);
#[doc(alias = "GDK_KEY_kana_RI")]
pub const kana_RI: Key = Key(ffi::GDK_KEY_kana_RI as u32);
#[doc(alias = "GDK_KEY_kana_... | Rust | 0 |
a = "2"
b = 4.25
print(a+b) #error | Python | 1 |
);
let fsp = usize::from(fsp);
let len = input.len();
let (input, len) = if fsp >= input.len() {
(input, len)
} else {
(&input[..fsp + round as usize], fsp + round as usize)
};
let frac = bytes_to_u32(input)? * TEN_POW[MICRO_WIDTH.checked_sub(len... | Rust | 0 |
stream),
cobalt_sender,
);
let _ = proxy.get_current();
std::mem::drop(proxy); // Close connection so `server_fut` completes.
let _ = server_fut.await;
assert_eq!(
cobalt_receiver
... | Rust | 0 |
print("Average Walker PPO Time Attack Reward:", PPO_attack.avg_reward())
ATLA_attack.load_attack("Adv_Traj/Walker_ATLA_Time")
print("Average Walker ATLA Random Reward:", ATLA_attack.time_attack_reward(num_traj=10, attack_type="Random"))
print("Average Walker ATLA Alternating Reward:", ATLA_attack.time_attack_reward(nu... | Python | 1 |
arg.__new__ = staticmethod(__new__)
original_init_subclass = arg.__init_subclass__
# We need slightly different behavior if __init_subclass__
# is a bound method (likely if it was implemented in Python)
if isinstance(original_init_subclass, MethodType):
... | Python | 1 |
e[Opcode::PUSH20.as_usize()] = eval_push20 as _;
table[Opcode::PUSH21.as_usize()] = eval_push21 as _;
table[Opcode::PUSH22.as_usize()] = eval_push22 as _;
table[Opcode::PUSH23.as_usize()] = eval_push23 as _;
table[Opcode::PUSH24.as_usize()] = eval_push24 as _;
table[Opcode::PUSH25.as_usize()] = eval_push25 as... | Rust | 0 |
# The following comments couldn't be translated into the new config version:
#change the firstRun if you want a different IOV
# eg to write payload to the oracle database
# replace CondDBCommon.connect = "oracle://cms_orcoff_int2r/CMS_COND_CSC"
# Database output service
import FWCore.ParameterSet.Config as cms
p... | Python | 1 |
o::<WarpError>::into)?;
let channels = channels.into_iter().map(Into::into).collect();
Ok(warp::reply::json(&ChannelsListResponseBody {
updated_at,
channels,
}))
}
pub async fn bilibili_channels_list(
query: ChannelsListRequestQuery,
db: Database,
) -> Result<Json, Rejection> {
... | Rust | 0 |
oc = "14: Interrupt Source: Port 9.6 interrupt; Interrupt Flag: P9IFG6"]
P9IV_14 = 14,
#[doc = "16: Interrupt Source: Port 9.7 interrupt; Interrupt Flag: P9IFG7; Interrupt Priority: Lowest"]
P9IV_16 = 16,
}
impl From<P9IV_A> for u8 {
#[inline(always)]
fn from(variant: P9IV_A) -> Self {
varia... | Rust | 0 |
ListId`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-securitygroupingress-sourceprefixlistid).
///
/// Update type: _Immutable_.
/// AWS CloudFormation replaces the resource when you change this property.
pub source_prefix_list_id:... | Rust | 0 |
ption']}\n"
if plugin.get("commands"):
for cmd in plugin["commands"][:3]: # Show top 3 commands
help_text += f" - `{cmd}` \n"
return {
"found": True,
"solution": "Available commands and features",
"response": help... | Python | 1 |
"""Add soft delete fields to events table
Revision ID: 118120f66269
Revises: f5a3932810c6
Create Date: 2025-08-12 18:14:21.436863
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '118120f66269'
down_revision = 'f5a3932810c6'
branch_labels = None
depends_on = Non... | Python | 1 |
if num.is_null() {
return Err(PyErr::fetch(ob.py()));
}
let buffer: [c_uchar; $byte_size] = [0; $byte_size];
let ok = ffi::_PyLong_AsByteArray(
ob.as_ptr() as *mut ffi::PyLongObject,
buff... | Rust | 0 |
pub fn initialize(cp: &mut Classpath) {
register_jni!(cp, Java_java_lang_Double_doubleToRawLongBits, Java_java_lang_Double_longBitsToDouble);
}
use crate::AsyncRayonHandle;
use rayon::ThreadPool;
use std::panic::{catch_unwind, AssertUnwindSafe};
use tokio::sync::oneshot;
/// Extension trait that integrates Rayon's... | Rust | 0 |
let p1 = self.pos * self.vertices[idx[0] as usize];
let p2 = self.pos * self.vertices[idx[1] as usize];
#[cfg(feature = "dim2")]
window.draw_planar_line(&p1, &p2, &self.color);
#[cfg(feature = "dim3")]
window.draw_line(&p1, &p2, &self.color);
... | Rust | 0 |
ialize, Debug)]
struct User {
name: String,
}
#[fn_handler]
async fn test() -> JsonContent<User> {
JsonContent(User { name: "jobs".into() })
}
let router = Router::new().push(Router::with_path("test").get(test));
let service = Service::new... | Rust | 0 |
_":
parser = ArgumentParser(description="Resample labels to desired distribution")
parser.add_arguments(DatasetOptions, dest="select_options")
parser.add_arguments(SelectOptions, dest="filter_options")
args = parser.parse_args()
print("Arguments", args)
select(args.select_options, args.filter... | Python | 1 |
("foo")`, whereas "blark" would yield `None`.
///
/// Originally from [clap] which is Copyright (c) 2015-2016 <NAME>
///
/// [clap]: https://github.com/kbknapp/clap-rs/blob/dc7ae65fb784dc355d56f09554f1216b22755c3e/src/suggestions.rs
pub fn did_you_mean<'a, T: ?Sized, I>(v: &str, possible_values: I) -> Option<&'a str>
w... | Rust | 0 |
}
fn assert_eq_fold_gt(c1: Const, c2: Const, c3: Const) {
let res = fold_gt(&ExprKind::Const(c1), &ExprKind::Const(c2))
.unwrap()
.unwrap();
assert_eq!(res, c3)
}
fn assert_eq_fold_ge(c1: Const, c2: Const, c3: Const) {
let res = fold_ge(&ExprKind::Const(c1)... | Rust | 0 |
for interface in obj:
if interface == HWSIM_INTERFACE_INTERFACE:
if obj[interface]['Address'] == radio.addresses[0]:
radio_path = path
break
iface = dbus.Interface(self._bus.get_object(HWSIM_SERVICE, radio_path),
... | Python | 1 |
att = att_resource.createAttribute('test', defn)
self.assertIsNotNone(att, 'failed to create test attribute')
# Create builder and apply config spec (dictionary)
builder = smtk.attribute_builder.AttributeBuilder()
resource_dict = dict(model=model_resource)
builder.build_attribut... | Python | 1 |
pallet_prelude::*};
use frame_support::{
dispatch::DispatchResult,
ensure,
traits::{Get, LockableCurrency, LockIdentifier, WithdrawReasons},
weights::{DispatchClass, Weight},
};
use frame_system::ensure_signed;
use frame_system::pallet_prelude::*;
use sp_runtime::{
Perbill,
traits::{CheckedAdd, Saturat... | Rust | 0 |
w(RefCell::new(1));
let mut r2 = SendRc::clone(&r1);
let pre_send1 = SendRc::pre_send();
pre_send1.park(&mut r1);
pre_send1.park(&mut r2);
let pre_send2 = SendRc::pre_send();
let _ref1: &RefCell<u32> = pre_send2.park(&mut r1); // this must panic
let post_send = pr... | Rust | 0 |
//ValidAccountId::try_from(account.to_string()).expect("Invalid account")
let result: AccountId = AccountId::new_unchecked(account.to_string());
result
}
fn get_context(deposit: Balance) -> VMContextBuilder {
let mut builder = VMContextBuilder::new();
builder.predecesso... | Rust | 0 |
ve,
rsa_private_key['modulus'].native
)
return int_to_bytes(transformed_int, width=private_key.asn1.byte_size)
def raw_rsa_public_crypt(certificate_or_public_key, data):
"""
Performs a raw RSA algorithm in a byte string using a certificate or
public key. This is a low-level primitive and i... | Python | 1 |
# Copyright (c) Alibaba, Inc. and its affiliates.
import os
import unittest
import cv2
from tests.ut_config import BASE_LOCAL_PATH, PRETRAINED_MODEL_FACE_2D_KEYPOINTS
from easycv.predictors.face_keypoints_predictor import FaceKeypointsPredictor
class FaceKeypointsPredictorWithoutDetectorTest(unittest.TestCase):
... | Python | 1 |
cType.SENSOR, DataType.ANALOG), # pressure meter; RO feed pressure
('PIT502', 5, SrcType.SENSOR, DataType.ANALOG), # pressure meter; RO permeate pressure
('PIT503', 5, SrcType.SENSOR, DataType.ANALOG), # pressure meter; RO reject pressure
# 'P601' [actuator] pump; pumps water from RO permeate tank to r... | Python | 1 |
}
}
}
impl fmt::Display for ThemedIcon {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ThemedIcon")
}
}
<gh_stars>0
use super::*;
use crate::{RafxRootSignature, RafxSampler, RafxShader, RafxShaderModule};
use rafx_base::DecimalF32;
use std::hash::{Hash, Hasher};
use fn... | Rust | 0 |
, meta_item),
}
}
fn table_name(cx: &mut ExtCtxt, meta_item: &MetaItem) -> InternedString {
match meta_item.node {
MetaItemKind::Word(ref word) => word.clone(),
_ => usage_error(cx, meta_item),
}
}
fn usage_error(cx: &mut ExtCtxt, meta_item: &MetaItem) -> ! {
cx.span_err(meta_item.span... | Rust | 0 |
println!("Error occured while running batch job:\n{}", e);
return;
}
if let Err(why) = bj.save_to_file() {
println!("Error while writing batch job to file: {}", why);
return;
}
} else if let Some(matches_run) = matches.subcommand_matches("run"... | Rust | 0 |
import paddle
import numpy as np
import pickle
import sys
f = open('result.txt', 'w')
f.write("======mmdetection_YOLOv3: \n")
try:
paddle.enable_static()
exe = paddle.static.Executor(paddle.CPUPlace())
# test Dygraph
[prog, inputs, outputs] = paddle.static.load_inference_model(
path_prefix="pd_... | Python | 1 |
.
/// * `get_register_value`: Function that returns the value of a register or the base address of a segment register, or `None` for unsupported
/// registers.
///
/// # Call-back function args
///
/// * Arg 1: `register`: Register (GPR8, GPR16, GPR32, GPR64, XMM, YMM, ZMM, seg). If it's a segment register, th... | Rust | 0 |
"""Siren support for switch entities."""
from __future__ import annotations
from homeassistant.components.siren import (
DOMAIN as SIREN_DOMAIN,
SirenEntity,
SirenEntityFeature,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ENTITY_ID
from homeassistant.core imp... | Python | 1 |
by_field_name("value").unwrap());
if let Ok(value) = value {
let value = S::new(value, name.span);
annotations.insert(name.node, value);
}
}
annotations
}
pub fn path(source: &Source, node: Node) -> S<Path> {
let cursor = &mut node.walk();
S::create(Path(node.named_children(cursor)
.map(|node| identifi... | Rust | 0 |
['Target'] = f'media/{new_file_name}'
base_rels_root.append(new_rel)
print(f"添加媒体关系: {old_id} -> {new_id}, {media_file} -> {new_file_name}")
break
# 8. 保存更新后的关系文件
base_rels_tree.write(ba... | Python | 1 |
token,
amount,
fee,
nonce,
time_range: Some(time_range),
signature: signature.clone().unwrap_or_default(),
cached_signer: VerifiedSignatureCache::NotCached,
};
if signature.is_some() {
tx.cached_signer = Ver... | Rust | 0 |
opt_def_id: Option<ast::DefId>,
fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
mk_t(cx, ty_bare_fn(opt_def_id, fty))
}
pub fn mk_ctor_fn<'tcx>(cx: &ctxt<'tcx>,
def_id: ast::DefId,
input_tys: &[Ty<'tcx>],
output: Ty... | Rust | 0 |
(self, window_seconds: float = 300.0) -> float:
"""获取故障率"""
current_time = time.time()
cutoff_time = current_time - window_seconds
recent_checks = [(t, healthy) for t, healthy in self.health_history if t > cutoff_time]
if not recent_checks:
return 0.0
failur... | Python | 1 |
Conditional::new(
Command::new("false", vec![]),
AST::Block(Block(vec![])),
Some(AST::If(Conditional::new(
Command::new("false", vec![]),
AST::Block(Block(vec![])),
None
... | Rust | 0 |
_of_children {
let child = parse_tree(input)?;
children.push(child);
}
let mut metadata = vec![];
for _i in 0..number_of_metadata {
metadata.push(next_number(input)?);
}
let root = Node { children, metadata };
Ok(root)
}
fn metadata_sum(root: &Node) -> i32 {
let mut sum = root.metadata.iter... | Rust | 0 |
# From https://github.com/AntoninGranados/Minidisk
import numpy as np
from copy import deepcopy
def ellipse_through(points):
if len(points) == 0:
return np.zeros((2,2))
if len(points) == 1:
return np.zeros((2,2))
if len(points) == 2:
p1 = np.array(points[0])
p2 = np.array(points[1])
A = np.outer(p1, ... | Python | 1 |
ha='center', va='bottom', color='red', fontweight='bold', fontsize=9,
bbox=dict(boxstyle="round,pad=0.3", facecolor='white', edgecolor='red', alpha=0.8))
# Formatting
ax.set_yticks(range(len(MACHINE_LIST)))
ax.set_yticklabels(MACHINE_LIST)
ax.... | Python | 1 |
"""
Provides functions for calculating the formula-based specification of the
`QuadraticForm` program.
This module defines two functions for deriving specifications with respect
to pure-state test cases (PSTCs) and mixed-state test cases (MSTCs).
The calculations are performed on CPU using algebraic operations on stat... | Python | 1 |
>,
/// Energy conservation program exception.
#[serde(rename="energyConservationProgramException")]
pub energy_conservation_program_exception: Option<String>,
/// Energy efficient heating and cooling systems. The property doesn't use chlorofluorocarbon (CFC)-based refrigerants in heating, ventilating, a... | Rust | 0 |
from sklearn.model_selection import GridSearchCV
def tune_hyperparameters(pipeline, X, y):
# Expanded search space
param_grid = {
'gbr__n_estimators': [200, 300, 400],
'gbr__learning_rate': [0.01, 0.05, 0.1],
'gbr__max_depth': [3, 5, 7],
'gbr__min_samples_split': [2, 4, 6]
... | Python | 1 |
= unpack(sol.x)
pvarsopt = p.problem_variables(decopt)
xopt = decopt['xbar']
popt = decopt['p']
qopt = decopt['q']
sPcorropt = pvarsopt['S_x']
# Get Riccatti solution
A = jax.jacobian(model._trans_mean)(xopt[0], u[0], popt, qopt, dt)
C = jax.jacobian(model.h)(xopt[0], u[0], popt, qopt)... | Python | 1 |
Fd};
use sys;
/// Use dup2 to replace `old` with `new` using `old`s file descriptor ID
pub(crate) fn redir(old: RawFd, new: RawFd) {
if let Err(e) = sys::dup2(old, new) {
eprintln!("ion: could not duplicate {} to {}: {}", old, new, e);
}
}
/// Duplicates STDIN, STDOUT, and STDERR; in that order; and r... | Rust | 0 |
"),
assigned_number!("FDEC", "Mannkind Corporation"),
assigned_number!("FDED", "Pole Star"),
assigned_number!("FDEE", "Huawei Technologies Co., Ltd."),
assigned_number!("FDEF", "ART AND PROGRAM, INC."),
assigned_number!("FDF0", "Google Inc."),
assigned_number!("FDF1", "LAMPLIGHT Co.,Ltd"),
a... | Rust | 0 |
m(0).float() / ((pred | gt).sum(0).float() + 1e-5) # Calculate IoU: (pred * gt).sum(0) represents intersection, (pred | gt).sum(0) represents union. .sum(0) calculates the sum across all dimensions column-wise.
IOUs.append(iou.cpu().numpy())
precision_half = (iou > 0.5).sum().float() / iou.shape[0]
... | Python | 1 |
#
# Copyright (C) 2009-2020 the sqlparse authors and contributors
# <see AUTHORS file>
#
# This module is part of python-sqlparse and is released under
# the BSD License: https://opensource.org/licenses/BSD-3-Clause
import re
from sqlparse import tokens
def is_keyword(value):
"""Checks for a keyword.
If th... | Python | 1 |
.all(spacing[0] == spacing)) and p_norm <= 2:
# For unity spacing we can make the borders more sparse by using a
# lower connectivity
footprint = ndi.generate_binary_structure(out.ndim, 1)
else:
footprint = ndi.generate_binary_structure(out.ndim, out.ndim)
border = (
ndi.... | Python | 1 |
;
}
extern "C" {
pub fn asContext_GetReturnWord(c: *mut asIScriptContext) -> asWORD;
}
extern "C" {
pub fn asContext_GetReturnDWord(c: *mut asIScriptContext) -> asDWORD;
}
extern "C" {
pub fn asContext_GetReturnQWord(c: *mut asIScriptContext) -> asQWORD;
}
extern "C" {
pub fn asContext_GetReturnFloat(c:... | Rust | 0 |
egs.get_flags() & FLAG_CARRY) != 0;
let mut flags = 0u8;
match alu_code {
// ADD A, Operand
U3::N0 => {
let temp: u16 = (acc as u16).wrapping_add(operand as u16);
result = temp as u8;
// get lookup code in r12 form [read file overflows.rs in `tables` module]
... | Rust | 0 |
from scipy import ndimage
from Nii_utils import NiiDataWrite, NiiDataRead
import os
import numpy as np
import shutil
data_dir = r'preprocessed_data'
for pats in ['train-pats', 'validation-pats', 'test-pats']:
save_dir = os.path.join(data_dir, '{}_preprocess'.format(pats))
for ID in os.listdir(os.path.join(dat... | Python | 1 |
from pandac.PandaModules import *
from pirates.seapatch.SeaPatchNode import SeaPatchNode
from otp.otpbase import OTPRender
class WaterShadow(NodePath):
def __init__(self, name, shadow_model, parent, use_water_bin=True, bin_number=7):
self.name = name
self.use_water_bin = use_water_bin
self... | Python | 1 |
ut
.send(Ok(ChanCell::new(23.into(), relaycell.clone())))
.await
.unwrap();
reactor.run_once().await.unwrap(); // should be fine.
}
// This one will fail.
input
.send(Ok(ChanCell::new(23.into... | Rust | 0 |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that 'copies' with app bundles are handled correctly.
"""
import TestGyp
import os
import sys
import time
if sys.platform ==... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class SignItemRole(models.Model):
_inherit = "sign.item.role"
auth_method = fields.Selection(selection_add=[
('itsme', 'Via itsme®')
], ondelete={'itsme': 'cascade'}... | Python | 1 |
ral["summarize", "update_memory"]:
"""Decide whether to summarize based on message count."""
message_count = len(state["messages"])
if message_count > MAX_MESSAGES_BEFORE_SUMMARY:
# print(" Decision: Summarize") # Reduce noise
return "summarize"
else:
# print(" Decision: Contin... | Python | 1 |
from typing import List, Tuple, cast
from thinc.api import (
Linear,
Logistic,
Maxout,
Model,
chain,
concatenate,
glorot_uniform_init,
list2ragged,
reduce_first,
reduce_last,
reduce_max,
reduce_mean,
with_getitem,
)
from thinc.types import Floats2d, Ragged
from ...t... | Python | 1 |
let lhs = lhs.as_string().unwrap();
let rhs = rhs.as_string().unwrap();
let regex: Regex = Regex::new(rhs).unwrap();
regex.is_match(lhs)
}
})
}
}
}
// --------------------------------------------------------------------... | Rust | 0 |
from typing import Annotated
from fastapi import Depends, HTTPException, Security
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from src.config.settings import settings
from src.services.translation_service import NLLBTranslationService
# Global service instance
translation_service = NLLBTran... | Python | 1 |
// must be 0 (system)
dpl : 2; // descriptor(meaning new) privilege level
p : 1; // Present
off_31_16 : 16; // high bits of offset in segment
*/
#[repr(C, packed)]
#[derive(Clone, Copy)]
struct GateDescriptor(u32, u32);
impl GateDescriptor {
pub const TYPE_INTERRUPT_GATE_32: u8 = 0xe;
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.