text string | label_name string | labels int64 |
|---|---|---|
e();
assert!(clocks.is_pll48clk_valid());
defmt::info!("clocks.hclk: {}", clocks.hclk().raw());
defmt::info!("clocks.pclk1: {}", clocks.pclk1().raw());
defmt::info!("clocks.pclk2: {}", clocks.pclk2().raw());
defmt::info!("clocks.pll48clk: {}", clocks.pll48clk().unwrap().raw());... | Rust | 0 |
ous().view(B * D, C, H, W)
#
# # TODO : CNN-model
# # x = self.backbone(x)[0]
# x = self.multiscale_feature(x) # (64, 2048, 1, 1)
#
# # x = self.conv_tmp(x)
# # x = self.cbam(x)
# x = self.eca(x)
#
# # 消融实验pool和transformer
# # TODO: 3D-pool
# # _C... | Python | 1 |
import time
class GithubMixin(object):
def query_github_api(self, endpoint, payload={}, options={}):
opts = {'max_pages': None}
opts.update(options)
headers = {'Authorization': f"token {self.get_key('github_api')}"}
base_url = 'https://api.github.com'
url = base_url + endp... | Python | 1 |
# -*- coding: utf-8 -*-
# @Author : relakkes@gmail.com
# @Time : 2024/4/5 10:13
# @Desc :
from .jishu_http_proxy import new_jisu_http_proxy
from .kuaidl_proxy import new_kuai_daili_proxy | Python | 1 |
/publickey.rs
use super::ecdsa::*;
use super::eddsa::*;
use super::rsa::*;
use super::*;
use crate::asymmetric_common::*;
use crate::error::*;
#[derive(Clone, Debug)]
pub enum SignaturePublicKey {
Ecdsa(EcdsaSignaturePublicKey),
Eddsa(EddsaSignaturePublicKey),
Rsa(RsaSignaturePublicKey),
}
impl SignaturePu... | Rust | 0 |
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
],
use_udp=True),
dict(
type='Collect',
keys=['img'],
meta_keys=[
'image_file', 'aug_data', 'test_scale_factor', 'base_size',
'center', 'scale', 'flip_index'
... | Python | 1 |
# modify nudge_coef for tracer
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
import scipy.io
from lo_tools import plotting_functions as pfun
import pickle
from lo_tools import zrfun
# old nudge file (generate from pgrid)
ds = xr.open_dataset('nudgcoef.nc')
#M2_NudgeCoef = ds.M2_NudgeCoef.value... | Python | 1 |
/// Obtain the memory map
pub fn get_memory_map() -> &'static[::memory::MemoryMapEnt]
{
get_bootinfo().memmap()
}
// vim: ft=rust
//! [`#[you_can::turn_off_the_borrow_checker]`][turn_off_the_borrow_checker]
#![no_std]
#![allow(clippy::needless_doctest_main)]
#![warn(unused_extern_crates)]
#![deny(unsafe_op_in_unsafe... | Rust | 0 |
),
Sphere::new(na::Vector3::new(7., 5., -18.), 4., mirror),
];
let light = vec![
Light::new(na::Vector3::new(-20., 20., 20.), 1.5),
Light::new(na::Vector3::new(30., 50., -25.), 1.8),
Light::new(na::Vector3::new(30., 20., 30.), 1.7),
];
render(&elements, &light)?;
O... | Rust | 0 |
-> Result<(), Error> {
//! let key: Hmac<Sha256> = Hmac::new_from_slice(b"some-secret")?;
//! let mut claims = BTreeMap::new();
//! claims.insert("sub", "someone");
//! let token_str = claims.sign_with_key(&key)?;
//! assert_eq!(token_str, "<KEY>");
//! # Ok(())
//! # }
//! # try_main().unwrap()
//! ```
//! #### Verif... | Rust | 0 |
eros_like(re_right))
ner_right_mask = self.get_right_entity_pair(ner_pred, ner_label)
re_right = re_right * ner_right_mask
right_num = re_right.sum().item()
triple_num_list += [pred_num, gold_num, right_num]
return triple_num_list
def count_ner_num(self, n... | Python | 1 |
import matplotlib.pyplot as plt
import numpy as np
import scipy
import SLUIRP.plotting.external_plots
import SLUIRP.plotting.sim_plots
import pandas
def CD_estimate(time,alt, vel, accel, density, area, mass):
df1 = pandas.read_csv("CSV_files/TestHuntsville.csv", index_col=None)
testtime = np.array(df1[df1.colu... | Python | 1 |
let v = Vector2DFloat::new((1.1, 2.1), (3.9, 4.7));
assert_relative_eq!(v.magnitude(), 3.82099463490856);
}
#[test]
fn vector2float_begin() {
let v = Vector2DFloat::new((1.0, 2.0), (3.0, 4.0));
assert_relative_eq!(v.begin().x, 1.0);
assert_relative_eq!(v.begin().y, 2... | Rust | 0 |
lt.plot(range(1, 13), predicted_sales_2025, marker='o', color='b', linestyle='-', label='Forecast Sales 2025')
plt.title('Average Training Predictions vs. Forecast Sales 2025')
plt.xlabel('Month')
plt.ylabel('Sales (boxes)')
plt.xticks(range(1, 13), ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'Augu... | Python | 1 |
jumbograms.
// More importantly, individual OSs can have their limit much lower!
const MAX_PACKET_SIZE: usize = 65535;
pub(super) struct UdpState {
logger: KompactLogger,
pub(super) socket: UdpSocket,
outbound_queue: VecDeque<(SocketAddr, SerialisedFrame)>,
input_buffer: DecodeBuffer,
pub(super) i... | Rust | 0 |
: "az",
tts: Some("kəsişən bayraqlar"),
keywords: &["bayram", "kəsişən", "kəsişən bayraqlar", "xaç", "yapon"],
},
#[cfg(feature = "be")]
crate::Annotation {
lang: "be",
tts: Some("скрыжаваныя сцягі"),
keywords: &[
"свята... | Rust | 0 |
server: &mut Server<ClusterConfiguration<usize>, (), usize>
) {
let (completed_sender, completed_receiver) = oneshot::channel();
server.send(Command::Synchronize(completed_sender)).await.unwrap();
let _ = completed_receiver.await;
}
async fn cast_vote(
server: &mut Server<ClusterConfiguration<usize... | Rust | 0 |
{ kind: ClientSessionErrorKind::ChunkSerializationError(kind) }
}
}
impl From<ChunkDeserializationError> for ClientSessionError {
fn from(kind: ChunkDeserializationError) -> Self {
ClientSessionError { kind: ClientSessionErrorKind::ChunkDeserializationError(kind) }
}
}
impl From<MessageSerializati... | Rust | 0 |
SVG_LENGTH {
D2D1_SVG_LENGTH {
value: self.value,
units: self.units as u32,
}
}
}
#[derive(Clone, Debug)]
pub struct SVGPreserveAspectRatio {
pub defer: bool,
pub align: SVGAspectAlign,
pub meet_or_slice: SVGAspectScaling,
}
impl SVGPreserveAspectRatio {
fn t... | Rust | 0 |
"""
Header component of the dashboard.
"""
import dash_mantine_components as dmc
from dash_iconify import DashIconify
from ...webapp.dashboard import config
header_contents = dmc.Grid(
align="center",
justify="space-between",
children=[
dmc.GridCol(
dmc.Group(
[
... | Python | 1 |
and rate > 150) or (("IMAP" in row[0] and rate > 10 and row[7][0] == '8') or row[0] == 'FTP_filetransfer' and total_time > 20 and rate > 100) or ( rate > 10 and "SFTP" in row[0])): #for CICNTTor_file
# if total_time > 20 and rate > 5: #for CICNTTor_file_tor
# if ("skype" in row[... | Python | 1 |
"""Tests covering the finite difference pricing engine import surface."""
import pathlib
import sys
# Ensure project root on path
sys.path.append(str(pathlib.Path(__file__).resolve().parents[1]))
from src.pricing import (
GridParameters,
PricingEngine,
PricingResult,
create_default_pricing_engine,
)
f... | Python | 1 |
class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
tuple_heap = [] # Stores (value, index) as min heap
for i, val in enumerate(nums):
if len(tuple_heap) == k:
heappushpop(tuple_heap, (val, i)) # To prevent size of heap growing larger than k
... | Python | 1 |
pro_uart_intr_map::PRO_UART_INTR_MAP_SPEC>;
#[doc = "UART_INT interrupt configuration register"]
pub mod pro_uart_intr_map;
#[doc = "PRO_UART1_INTR_MAP register accessor: an alias for `Reg<PRO_UART1_INTR_MAP_SPEC>`"]
pub type PRO_UART1_INTR_MAP = crate::Reg<pro_uart1_intr_map::PRO_UART1_INTR_MAP_SPEC>;
#[doc = "UART1_I... | Rust | 0 |
"storages.backends.s3boto3.S3Boto3Storage",
},
}
# Email Config
EMAIL_BACKEND = (
"django.core.mail.backends.console.EmailBackend"
if DEBUG
else "django.core.mail.backends.smtp.EmailBackend"
)
EMAIL_HOST = config("EMAIL_HOST", cast=str)
EMAIL_PORT = config("EMAIL_PORT", cast=int, default=465)
EMAIL_US... | Python | 1 |
r_lite_interpreter())
buffer.seek(0)
self.mobile_module = _load_for_lite_interpreter(buffer)
def test_execution(self):
a = torch.ones(1)
b = 3 * torch.ones(1)
s = 3
# Test forward.
self.check_function("forward", (a, b, s))
class AddedAttributesTest(JitBacke... | Python | 1 |
ly")
def test_attribute_error_prevention():
"""Test that the original AttributeError issue is resolved."""
print("\nTesting AttributeError prevention...")
try:
# These should not raise AttributeError anymore
starting = StoryArc.STARTING_THRESHOLD
developing = StoryArc.DEVELOPI... | Python | 1 |
se:
x_a = round(x_min / 2 - radius + x_max / 2)
x_b = round(x_max / 2 + radius + x_min / 2)
if y_max - y_min + 1 >= 2 * radius:
y_a, y_b = y_min, y_max
else:
y_a = round(y_min / 2 - radius + y_max / 2)
y_b = round(y_max / 2 + radius + y_min / 2)
if z_max - z_min + 1 >... | Python | 1 |
hook ,,99.__%00%/%>%>%K%K%M++)99
N 0__&33)99 N ((77+//1N(3r= r )rH r3 r{ r| r} s ` r: _sharded_post_state_dict_hookr
= )tCH~ )s ) ), 0
J
r= c [ X5 ( a+ [... | Python | 1 |
"stx", "sax",
"bcc", "sta", "kil", "ahx", "sty", "sta", "stx", "sax", "tya", "sta", "txs", "tas",
"shy", "sta", "shx", "ahx", "ldy", "lda", "ldx", "lax", "ldy", "lda", "ldx", "lax",
"tay", "lda", "tax", "lax", "ldy", "lda", "ldx", "lax", "bcs", "lda", "kil", "lax",
"ldy", "lda", "ldx", "lax", "clv", "l... | Rust | 0 |
ressurized(time + 1);
vacuum.push_back(next_coord);
}
}
} else {
panic!("expect pressurized tile in vacuum list")
}
}
// find maximum pressurization time
m.values().flat_map(|t| match t {
Tile::Pressurized(time) => Some(*ti... | Rust | 0 |
WaitForThreadExit(0x000A, 0x0001)
@scena.Lambda('lambda_5B71')
def lambda_5B71():
ChrWalkTo(0x00FE, 2810, 4000, 39910, 3000, 0x00)
ExitThread()
DispatchAsync(0x000A, 0x0001, lambda_5B71)
WaitForThreadExit(0x000A, 0x0001)
@scena.Lambda('lambda_5B91')
def lambda_5B91():
... | Python | 1 |
("SERVERS_TO_PING")
.help("Servers to ping")
.index(1)
.required(true)
.multiple(true),
)
.get_matches();
if matches.is_present("servers") {
let servers = matches.values_of("servers").unwrap().collect::<Vec<_>>();
let t... | Rust | 0 |
class Solution:
def minimumFlips(self, root: Optional[TreeNode], result: bool) -> int:
# dp(root, target) := min flips to make the subtree root become target
@functools.lru_cache(None)
def dp(root: Optional[TreeNode], target: bool) -> int:
if root.val in (0, 1): # Leaf
return 0 if root.val ... | Python | 1 |
TAG.Point,
TAG.Emergency,
TAG.Air,
TAG.Flow,
TAG.System,
TAG.Status,
],
},
"Emergency_Power_... | Python | 1 |
color: &[f32; 3],
) -> ResourceId<Material> {
let color_node = pools.borrow_mut::<Box<dyn MaterialNode>>().add(
Box::new(Vector3Node::new(
*Color::copy(&mut Color::create(), color),
)),
);
pools.borrow_mut::<Material>().add(Material::new(color_node, Side::default()))
}
pub fn create_basic_materia... | Rust | 0 |
ode segment
"{rdi}"(ip) // IP
: // No clobers because it never returns
: "intel", "volatile");
unreachable!();
}
pub mod rocksdb;
// Don't create a new standard console window when launched from the windows GUI.
#![windows_subsystem = "windows"]
use failure::{err_msg, format_err, Error,... | Rust | 0 |
# class Member:
# def __init__(self) :
# self.name = "Abdellah"
# member_one = Member()
# member_two = Member()
# member_three = Member()
class Member:
def __init__(self,first_Name,midlle_Name,last_Name) :
self.fname = first_Name
self.mname = midlle_Name
self.lname = last_N... | Python | 1 |
crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_hs_hptxfsiz](otg_hs_hptxfsiz) module"]
pub type OTG_HS_HPTXFSIZ = crate::Reg<u32, _OTG_HS_HPTXFSIZ>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _OTG_HS_HPTXFSIZ;
#[doc = "... | Rust | 0 |
from django.contrib import admin
from my_app.models import *
admin.site.register(Marka)
admin.site.register(Model)
admin.site.register(Index)
admin.site.register(Index_About)
admin.site.register(Product)
admin.site.register(About)
admin.site.register(Ask)
admin.site.register(Blog)
admin.site.register(Contact)
admin.si... | Python | 1 |
.append(kl_div.item())
clip_fractions.append(clip_fraction.item())
# Reset buffer for next rollout
self.buffer.reset()
self.num_updates += 1
# Compute explained variance
with torch.no_grad():
y_true = data['returns'].cpu().numpy()
... | Python | 1 |
set_id(id);
view
}
pub(crate) fn id(&self) -> ObjID {
self.kso.obj.id()
}
pub(crate) fn lock_entry(&mut self, slot: usize) {
let hdr = self.kso.base_data_mut();
let entry = &mut hdr.entries[slot];
let old = entry.lock.fetch_add(1, Ordering::SeqCst);
if old == u32::MAX {
panic!("failed to lock slot ... | Rust | 0 |
, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0
]
);
assert_eq!(
notes,
[
15, 16, 17, 18, 18, 19... | Rust | 0 |
import torch
import torch.nn as nn
from datasets import load_dataset
from tqdm import tqdm
def evaluate_perplexity(model, tokenizer):
def _perplexity(nlls, n_samples, seqlen):
return torch.exp(torch.stack(nlls).sum() / (n_samples * seqlen))
# load and prepare dataset
data = load_dataset("wikitext... | Python | 1 |
ent).update(decklist_url="")
players_id = [s[0] for s in event.result_set.values_list("player_id")]
players = Player.objects.filter(id__in=players_id)
# Skip header row
next(reader)
found_rows = 0
total_rows = 0
for row in reader:
first, last, url, ... | Python | 1 |
struct a CodedConcept for a pydicom Code.
Parameters
----------
code: Union[pydicom.sr.coding.Code, highdicom.sr.CodedConcept]
Code.
Returns
-------
highdicom.sr.CodedConcept:
CodedConcept dataset for the code.
"""
if isinstance(... | Python | 1 |
time_to_unzip: self.time_to_unzip + other.time_to_unzip,
time_to_parse: self.time_to_parse + other.time_to_parse,
time_to_image: self.time_to_image + other.time_to_image,
}
}
}
enum BookState {
Invalid,
Ignored,
WholeZip,
Valid(Box<Book>),
}
impl Defaul... | Rust | 0 |
(HuffmanNode::Leaf(me), HuffmanNode::Leaf(other)) => me.symbol.cmp(&other.symbol),
(HuffmanNode::Branch(me), HuffmanNode::Branch(other)) => me.links.0.cmp(&other.links.0),
}
}
}
#[derive(PartialEq, Eq, Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Huff... | Rust | 0 |
return "\n\n".join(context_parts)
# Use the identified topics to find relevant scenes
if topics and self.vector_store:
search_query = " ".join(topics)
results = self.vector_store.query(
search_query,
top_k=3,
... | Python | 1 |
solve_arg(
secondary_arg.argument, True
)
metadata_to_table[
(metadata, thingy.local_table.schema)
].add(secondary_arg.argument)
resolver._reso... | Python | 1 |
import sys
import serial
import os
import time
import Hobot.GPIO as GPIO
import multiprocessing
class drone_result:
def __init__(self, success:bool, message:str):
self.success = success
self.message = message
class drone_command_type(int) :
TAKE_OFF = 0x00
MOVE = 0x01
LAND = 0x02
cla... | Python | 1 |
a = '237'
a = a.replace('2', ' ')
a = int(a) * 10
a = str(a)
a = a.replace('0', '2')
print(a)
| Python | 1 |
t(cb: impl Fn(Option<MSG>) -> bool) {
start_with_sleep(10, cb);
}
pub fn start_with_sleep(sleep: u64, cb: impl Fn(Option<MSG>) -> bool) {
let mut msg: MSG = MSG::default();
loop {
let mut value: Option<MSG> = None;
unsafe {
if !bool::from(!PeekMessageW(&mut msg, HWND(0), 0, 0, P... | Rust | 0 |
et_string,
}
}
}
b'$' => PrivmsgTarget::ServerMask(IrcIdent(from_cstring(arg3.offset(1)))),
_ => PrivmsgTarget::User(IrcIdent(from_cstring(arg3))),
};
let arg4_eol = *word_eol.offset(4);
let message = from_cstring(arg4_eol.o... | Rust | 0 |
decode()
.unwrap();
let (width, height) = image.dimensions();
let mut point_sets = inkdrop::sample_points(&image, data.num_points, 1.0, false);
self.link.respond(
who,
Response::Points(UpdateData::from(width, ... | Rust | 0 |
ecursive_depth=0):
"""Normal order an expression with bosonic or fermionic operators. Note
that this normal order is not equivalent to the original expression, but
the creation and annihilation operators in each term in expr is reordered
so that the expression becomes normal ordered.
Parameters
... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... | Python | 1 |
#
# Copyright (c) 2012+ Anton Tyurin <noxiouz@yandex.ru>
# Copyright (c) 2011-2014 Other contributors as noted in the AUTHORS file.
#
# This file is part of Cocaine.
#
# Cocaine is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as publis... | Python | 1 |
ter._specs)])
)
return self.get_latest_version_within_specs(
specs,
versions=self.package.versions,
prereleases=self.prereleases
)
def get_hashes(self, version):
r = requests.get('https://pypi.org/pypi/{name}/{version}/json'.format(
... | Python | 1 |
d(x.1))
.unwrap()
.0
}
fn select(&self, root: MCTSNodeChild<G, MCTS>) -> (Vec<G::Move>, MCTSNodeChild<G, MCTS>) {
let mut history: Vec<G::Move> = Vec::new();
//let mut tree_pos = Some(root);
let mut last_node = root;
loop {
let last_node_clo... | Rust | 0 |
as_ref().unwrap();
write!(output, "44={}\u{01}", val )?; // FIELD_PRICE
}
if flds.stop_px.is_some() {
let val = flds.stop_px.as_ref().unwrap();
write!(output, "99={}\u{01}", val )?; // FIELD_STOPPX
}
if flds.peg_difference.is_some() {
let val = flds.peg_difference.as_re... | Rust | 0 |
import numpy as np
from numba import jit
from agents.special import std_quantile2, norm_quantile
jit_args = {'nopython': True, 'cache': True, 'fastmath': True}
@jit(**jit_args)
def policy_clt(nodes, visit, value, variance):
n = visit.sum()
_q = value + norm_quantile(n) * np.sqrt(variance / visit)
retur... | Python | 1 |
mu_start(0x10000, 0x10000 + len(X86_MMIO_CODE))
# now print out some registers
print(f">>> Emulation done. ECX={hex(mu.reg_read(UC_X86_REG_ECX))}")
except UcError as e:
print("ERROR: %s" % e)
if __name__ == '__main__':
test_x86_16()
test_i386()
print("=" * 35)
test_i386_ma... | Python | 1 |
indingType::Buffer {
has_dynamic_offset: false,
min_binding_size: Some(NonZeroU64::new(1).unwrap()),
ty: wgpu::BufferBindingType::Storage { read_only: false },
},
},
],
});
// Create pipeline layout from bind group
... | Rust | 0 |
tic_tokens = get_semantic_tokens_from_language_server(
workspace, robot_source_file
)
assert semantic_tokens.get("A.B") == "name"
assert semantic_tokens.get(".Append to list") == "keywordNameCall"
def test_library_names_with_different_case_should_be_highlighted(workspace):
robot_source_file =... | Python | 1 |
sion: u32,
check_utf8: bool,
find_indexes: BytesIndexKernel,
) -> OffsetChunkProducer<R, impl FnMut(&[u8], &mut Offsets)> {
OffsetChunkProducer {
name: name.into(),
inner: Reader::new(r, chunk_size, /*padding=*/ 128, check_utf8),
find_indexes: move |bs: &[u8], offs: &mut Offsets| uns... | Rust | 0 |
t.subplot(212)
plt.plot(gan_signal[0][0])
plt.title('gan')
plt.savefig(os.path.join(opt.save_dir,'gan_result.png'))
plt.close('all')
def showscatter3d(data):
label_cnt,_,label_num = label_statistics(data[:,3])
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
cnt =... | Python | 1 |
# -*- coding: utf-8 -*-
"""
[channeljoin.py]
Join Plugin
[Author]
Marcelo Benesciutti
[About]
Bot Will join a given channel in the server
[Commands]
>>> .channeljoin channel
bot joins the given channel
"""
class Plugin:
def __init__(self):
pass
def run(self, incoming, methods, info, bot_info):
... | Python | 1 |
from fastmcp import Context
import httpx
from typing import Literal, Optional
from config import API_BASE
async def get_candles(
market: str,
interval: Literal["minute1", "minute3", "minute5", "minute10", "minute15", "minute30", "minute60", "minute240", "day", "week", "month"],
count: int = 200,
to: Op... | Python | 1 |
RawFd for SctpStream {
unsafe fn from_raw_fd(fd: RawFd) -> SctpStream {
let sock = Socket::from_raw_fd(fd);
SctpStream(sock)
}
}
pub struct SctpListener(Socket);
impl SctpListener {
pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<SctpListener> {
let addr = parse_addr(addr)?;
... | Rust | 0 |
from_alipay_dict(d):
if not d:
return None
o = BenefitPlayLuckDrawTemplateInfo()
if 'code' in d:
o.code = d['code']
if 'display_info' in d:
o.display_info = d['display_info']
if 'end_time' in d:
o.end_time = d['end_time']
i... | Python | 1 |
from django.core.management.base import BaseCommand
from django.conf import settings
from awx.main.tasks.host_metrics import HostMetricTask
class Command(BaseCommand):
"""
This command provides cleanup task for HostMetric model.
There are two modes, which run in following order:
- soft cleanup
- -... | Python | 1 |
"""
Copyright 2024 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, software
d... | Python | 1 |
from pigframe.world import System
from component import *
class SysBallMovement(System):
def process(self):
print("ball movement")
for ent, (pos, vel) in self.world.get_components(Position, Velocity):
pos.x += vel.x
pos.y += vel.y
if pos.x < 16:
... | Python | 1 |
import os
from lib import utils
from metric_providers.container import ContainerMetricProvider
class NetworkIoCgroupContainerProvider(ContainerMetricProvider):
def __init__(self, sampling_rate, skip_check=False, containers: dict = None):
super().__init__(
metric_name='network_io_cgroup_contain... | Python | 1 |
>,
pub realm_authority: Option<Keypair>,
}
#[derive(Debug)]
pub struct TokenOwnerRecordCookie {
pub address: Pubkey,
pub account: TokenOwnerRecord,
pub token_source: Pubkey,
pub token_source_amount: u64,
pub token_owner: Keypair,
pub governance_authority: Option<Keypair>,
pub gov... | Rust | 0 |
ys_db = data_lock.write().await;
*birthdays_db = birthdays_dict;
}
Ok(())
}
pub async fn update_flag(ctx: &Context, date: Date<Utc>) -> CommandResult {
let date_lock = {
let data_write = ctx.data.read().await;
data_write
.get::<TodayDate>()
.expect("Expected a TodayDate")
.clone()
};
// set flag to... | Rust | 0 |
#!/usr/bin/python
"""ssl module."""
import socket
import ssl
from termcolor import colored
def ssl_cert():
"""Get the ssl cert of a website."""
print colored('Enter a URL to get its SSL cert', 'green')
target_url = raw_input(colored('(netpwn: ssl_cert) > ', 'red'))
try:
cert = ssl.get_serve... | Python | 1 |
threshold=0
)
for property_info in properties:
if dataset == 'wes' and property_info["count"] < 5:
continue
property_uri = property_info["predicate"]
# metadata
if property_uri in ground_truth_cardinalities:
metada... | Python | 1 |
# Copyright 2009-2015 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software 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 notice,
# this list of conditions ... | Python | 1 |
downloaded += 1
time.sleep(max(0.0, float(args.sleep)))
print(f"Fetched {seen} posts from r/{args.subreddit} ({args.sort}{' '+args.time if args.sort=='top' else ''}).")
print(f"Downloaded {downloaded} media items into {out_dir}")
except Redirect:
print(f"Error: r/{a... | Python | 1 |
} if hints.len() == 1 && hints[0] == Ipv6Addr::from_str("2001:db8:ffff:ffff:ffff:ffff:198.51.100.100").unwrap()))
}
/// Example from: https://github.com/MikeBishop/dns-alt-svc/blob/master/draft-ietf-dnsop-svcb-https.md#serviceform
#[test]
fn test_service_binding_multiple_parameters() {
// given
let mut bytes:... | Rust | 0 |
:take());
let mut rcc = dp.RCC.constrain();
let mut flash = dp.FLASH.constrain();
let clocks = rcc.cfgr.freeze(&mut flash.acr);
let mut gpioa = dp.GPIOA.split(&mut rcc.ahb);
let mut gpiob = dp.GPIOB.split(&mut rcc.ahb);
let serial_pair = SerialPair {
0: gpio... | Rust | 0 |
= match last_msg_sent_offset {
Some(offset) => out_map.msg_from_offset(offset)?,
None => ptr::null_mut(),
};
Ok(Self {
id: 0,
last_msg_sent,
out_maps: vec![out_map],
// drop pages to the broker if it already read them
... | Rust | 0 |
import math, random
import numpy as np, pandas as pd
from dataclasses import dataclass
from typing import List, Optional, Tuple, Dict
# -------------------- 挡位选择 --------------------
PROFILE = 'C' # 'A' 快速 / 'B' 均衡(推荐) / 'C' 彻底
# 三个挡位参数(范围、网格、分组容差、退火与精修细节)
PROFILES = {
'A': dict( # 快速档
tb_range=(2.0, 2... | Python | 1 |
import pytest
from ape.exceptions import ContractNotFoundError
from tests.conftest import geth_process_test
@geth_process_test
def test_get_proxy_from_explorer(
mock_explorer,
create_mock_sepolia,
project,
geth_account,
geth_provider,
chain,
):
"""
Simulated when you get a contract fr... | Python | 1 |
::std::fmt::Debug for SolarStatusProfile {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for SolarStatusProfile {
fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef {
::protob... | Rust | 0 |
{
trace!("Prefix not found");
return Ok(());
}
let args = &words[1..];
trace!("Command: {} Args: {:?}", command_name, args);
let cmd = match self.get(command_name) {
Some(c) => c,
None => {
trace!("No matching command fou... | Rust | 0 |
,
_ => {},
}
}
// Save the best, if any!
Share::sync(tx, rx, guide.take().map(|x| Share::Best(path.to_path_buf(), x)));
}
}
Ok(())
}
/// # Encode: Load Source.
///
/// This generates an [`Input`] and [`Candidate`] object from a given file
/// path, or dies trying.
fn _encode_source(path: &Path)... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from scipy.stats._distn_infrastructure import rv_frozen
from scipy.stats import rv_continuous
from .distribution import Distribution
class ScipyDist(Distribution):
"""Distribution wrapper for a frozen Scipy Stats Distribution object
Discrete random variables n... | Python | 1 |
ponents),
StreamInput::MM(mm) => process_move_made(mm, components),
}
}
fn process_req_sync(rs: &ReqSync, components: &Components) {
info!("Stream: Req Sync {:?}", rs);
match components.history_repo.get(&rs.game_id) {
Ok(maybe_history) => {
let history = maybe_history.unwrap_or_... | Rust | 0 |
plan that produces the record batch
pub fn make_scan_plan(batch: RecordBatch) -> std::result::Result<LogicalPlan, DataFusionError> {
let schema = batch.schema();
let partitions = vec![vec![batch]];
let projection = None; // scan all columns
LogicalPlanBuilder::scan_memory(partitions, schema, projection)... | Rust | 0 |
_output_set || data_url.is_binary() {
// Write raw bytes if the output is a file, or if the contents of this data URL has binary format
if file_output_set {
let mut handle = fs::File::create(output_file_path).unwrap();
handle.write_... | Rust | 0 |
######
# render depth #
# ###############
testbed.render_mode = ngp.Depth
# The testbed has already considered the scale for depth
depth = testbed.render(ref_depth.shape[1], ref_depth.shape[0], spp, True)
# Debug code #
if args.debug_... | Python | 1 |
;
pub mod Unique;
}
pub mod macros {
pub mod macros;
pub mod number;
}
pub use objects::Associative::*;
pub use objects::Callable::*;
pub use objects::Class::*;
pub use objects::Collection::*;
pub use objects::Comparabl... | Rust | 0 |
shold which is 1 + percent close to the bend.
The default is 0.2.
idx_min : int, optional
The minimum index of u that are allowed to be a threshhold.
The default is 10.
Returns
-------
u_thresh : float
Detected thresh
"""
du = u[1] - u[0]
... | Python | 1 |
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "Save System Prompt"... | Python | 1 |
: raw_slot_id,
data: rest,
} = u8::mc_deserialize(data)?;
has_next = raw_slot_id & 0x80 != 0;
let slot_id = raw_slot_id & 0x7F;
let Deserialized {
value: slot,
data: rest,
} = EquipmentSlot::deserialize_with_id(s... | Rust | 0 |
diffusion_train=dict(
beta_scheduler='linear',
diffusion_steps=1000,
model_mean_type='start_x',
model_var_type='fixed_large',
),
diffusion_test=dict(
beta_scheduler='linear',
diffusion_steps... | Python | 1 |
vm, args| match vm.get_args(args) {
[value] => Ok(Str(value.type_as_string().into())),
unexpected => {
unexpected_type_error_with_slice("koto.type", "a single argument", unexpected)
}
});
result
}
<reponame>duskmoon314/aw-pac<filename>d1-pac/src/tpadc/tp_int_fifo_ctrl.rs
#[d... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.