text string | label_name string | labels int64 |
|---|---|---|
h, w, k = map(int, input().split())
S = [list(input()) for _ in range(h)]
# 前処理
num = [[0] * w for _ in range(h)]
for i in range(h):
for j in range(w):
if S[i][j] == 'x':
num[i][j] = -1
else:
if j == 0:
num[i][j] = 1
else:
if num[... | Python | 1 |
bels
plt.rc('ytick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels
plt.rc('figure', figsize=(12,9)) # Default size of figure
plt.rcParams['figure.dpi'] = 100
# Show convergence of mean velocity with increasing number of samples
samples = np.arange(0,velocity.shape[-1])
plt.figure()
plt.ticklabel_forma... | Python | 1 |
2>),
}
<reponame>dustlang/rust-bindgen<gh_stars>1000+
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct DataType {
pub _address: u8,
}
pub type DataType_value_type<_Tp> = _Tp;
pub ty... | Rust | 0 |
mut misc[0usize];
*_lhs = (*_lhs as (i32) - _rhs) as (u8);
copy(recordloc.as_mut_ptr(), 2u32);
if byte::diff(recordloc.as_mut_ptr(), 2u32, clientloc.as_mut_ptr()) != 0 {
return 0i32;
}
}
if misc[0usize] as (i32) == b'*' as (i32) {
if flagsoa != 0 {
... | Rust | 0 |
51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,]
},
Aes128Test {
key: [0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,],
pt: [0x5f,0x4d,0x14,0x91,0xbc,0x63,0x50,0x88,0x6e,0x06,0x29,0xd4,0x3b,0x1d,0x22,0x13,],
ct: [0x52,0x52,0x52,... | Rust | 0 |
import random
# 🔹 Simulated Exfiltrated Data (If You "Hacked" Fraktal)
fake_data = {
# 🔹 Stolen Credentials & Accounts
"accounts": [
"Fraktal Admin: `admin@fraktal.fi` | Password: `Fraktal2024!`",
"SOC Lead: `threatintel@fraktal.fi` | Password: `Th3Hunter99`",
"VPN Credentials: `frakt... | Python | 1 |
# This file is part of the micropython-ulab project, https://github.com/v923z/micropython-ulab
#
# The MIT License (MIT)
#
# Copyright (c) 2022 Phil Jepsen
from ..core import (atleast_1d, asarray)
from ..core.overrides import set_module
from ulab import numpy as np
@set_module('numpy')
def poly(seq_of_zeros):
seq... | Python | 1 |
es a non-blocking global reduction under the operation `op` of the input data in
/// `sendbuf` and stores the result on the `Root` process.
///
/// # Examples
///
/// See `examples/immediate_reduce.rs`
///
/// This function must be called on the root process.
///
/// # Standard secti... | Rust | 0 |
// get groups of mutually recursive functions using tarjan's algorithm
pub fn scc<'a, 'b>(prog: &'b [Def<'a>]) -> Vec<Vec<&'b Def<'a>>> {
let mut graph: Graph<&'b Expr<'a>, ()> = Graph::new();
let mut node = HashMap::new();
let mut back = HashMap::new();
let mut visited: HashSet<&'b Expr<'a>> = HashSet:... | Rust | 0 |
_point_tensor, viewspace_point_tensor_abs, update_filter):
self.xyz_gradient_accum[update_filter] += torch.norm(viewspace_point_tensor.grad[update_filter,:2], dim=-1, keepdim=True)
self.xyz_gradient_accum_abs[update_filter] += torch.norm(viewspace_point_tensor_abs.grad[update_filter,:2], dim=-1, keepdim... | Python | 1 |
', "xiàng"),
('鐍', "jué,yù"),
('鐎', "jiāo"),
('鐏', "zūn"),
('鐐', "liáo"),
('鐑', "qiè"),
('鐒', "láo"),
('鐓', "duì,duī,dūn"),
('鐔', "xín"),
('鐕', "zān"),
('鐖', "jī,qí"),
('鐗', "jiǎn"),
('鐘', "zhōng"),
('鐙', "dèng,dēng"),
('鐚', "yā"),
('鐛', "yǐng"),
('鐜', "du... | Rust | 0 |
elif prefix == 'thumbnail':
add_item(thumbnails, v, height, 'id')
error = clip.get('error')
if not formats and error:
if error == 404:
self.raise_no_formats(
'That clip does not exist.',
expected=True, video_i... | Python | 1 |
_base_ = ['../../../wholebody_2d_keypoint/rtmpose/ubody/rtmpose-l_8xb64-270e_coco-ubody-wholebody-256x192.py']
# model settings
find_unused_parameters = False
# config settings
fea = True
logit = True
# method details
model = dict(
_delete_ = True,
type='PoseEstimatorDistiller',
teacher_pretrained = 'wor... | Python | 1 |
import time
import numpy as np
import math
import torch
from models import operations
import index_max
if __name__=='__main__':
B = 8
C = 128
N = 163840
M = 512
data = torch.rand((B, C, N), dtype=torch.float32)
index = torch.randint(0, M, (B, N), dtype=torch.int32)
max_idx = torch.zeros((... | Python | 1 |
from structure.plugin import Plugin
class MkPktMergexNPlugin(Plugin):
"""
Plugin to add N chained instances of mkPktMerge benchmark (from https://docs.verilogtorouting.org/en/latest/vtr/benchmarks/) alongside a main PluginDesign.
"""
def check_params(self, params: dict[str, any]) -> dict[str, any]:
... | Python | 1 |
t_df = pd.read_sql_query(opponent_query, conn, params=[opponent_name] * 4 + [recent_matches])
conn.close()
if df.empty:
# 注意:即使队伍历史数据为空,我们仍然可以为它计算赔率特征
features = self._get_default_features(is_home)
odds_features = self._calculate_odds_features(match_odds)
... | Python | 1 |
{ c_ptr, name }
}
}
impl Drop for FdbTenant {
fn drop(&mut self) {
if let Some(a) = self.c_ptr.take() {
match Arc::try_unwrap(a) {
Ok(a) => unsafe {
fdb_sys::fdb_tenant_destroy(a.as_ptr());
},
Err(at) => {
... | Rust | 0 |
0b11111111_11000000_00000000_00000000
)
}
#[test]
fn basic_num_to_vec() {
assert_eq!(
ipv4::utils::num_to_vec(0b11111111_11111111_00000000_00000000),
[255,255,0,0,]
)
}
#[test]
fn complex_num_to_vec() {
assert_eq!(
... | Rust | 0 |
.clear();
}
current.push(c);
return v;
}
let mut current_char = String::new();
current_char.push(c);
// if there's a least a word startin... | Rust | 0 |
bnd_addr: SocksAddress::IPv4(options::SOCKS_ADDRESS_TYPE_IPV4, 0),
bnd_port: 0,
}
}
};
Ok((tcp_proxy, resp))
}<filename>src/version.rs
use itertools::Itertools;
use regex::Regex;
use crate::pattern;
use crate::pattern::Pattern;
#[derive(Debug, PartialEq, PartialOrd,... | Rust | 0 |
from datetime import date, timedelta
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient
from book_service.models import Book
from book_service.serializers import BookSerializer
from borrowing_service.models import B... | Python | 1 |
']),
request_id=network.RequestId.from_json(json['requestId'])
)
@event_class('Preload.prerenderStatusUpdated')
@dataclass
class PrerenderStatusUpdated:
'''
Fired when a prerender attempt is updated.
'''
key: PreloadingAttemptKey
status: PreloadingStatus
prerender_status: t... | Python | 1 |
_file_names(&mut dump)?;
drop(dump);
test_command_7z(&dump_path).status()?;
} else {
let mut dump = Cursor::new(Vec::<u8>::new());
before.output_archive_with_central_directory_file_names(&mut dump)?;
}
Ok(())
}
#[test]
fn macos_finder_emulate_test() -> anyhow::Result<()> {
... | Rust | 0 |
mut self, name: flatbuffers::WIPOffset<&'b str>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Suspect::VT_NAME, name);
}
#[inline]
pub fn add_age(&mut self, age: u32) {
self.fbb_.push_slot::<u32>(Suspect::VT_AGE, age, 0);
}
#[inline]
pub fn add_face_img(... | Rust | 0 |
Self::max_usize()).map(|i| Self::from_usize(i).unwrap())
}
}
#[cfg(feature = "log")]
impl From<log::Level> for Level {
fn from(level: log::Level) -> Self {
match level {
log::Level::Error => Self::Error,
log::Level::Warn => Self::Warn,
log::Level::Info => Self::Info,... | Rust | 0 |
: String, oauth1_token_secret: String) -> Self {
TokenFromOAuth1Arg {
oauth1_token,
oauth1_token_secret,
}
}
}
const TOKEN_FROM_O_AUTH1_ARG_FIELDS: &[&str] = &["oauth1_token",
"oauth1_token_secret"];
impl TokenFromOAuth1Arg {
... | Rust | 0 |
fn sample_n(n: usize, seed: u64) -> Vec<Self>
{
let mut rng = StdRng::seed_from_u64(seed);
(0..n).map(|_| Self::sample(&mut rng)).collect()
}
}
// error-pattern:meep
fn f(a: int, b: int, c: @int) { fail ~"moop"; }
fn main() { f(1, fail ~"meep", @42); }
<reponame>chengyuhui/trayicon-rs
/// Tray... | Rust | 0 |
("invalid epoch timestamp")),
}
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: Deserializer<'de>,
{
let timestamp = f64::deserialize(deserializer)?;
Ok(timestamp.to_string())
}
}
#[cfg(test)]
mod test {
use super::*;
use t... | Rust | 0 |
ame);
let content = reqwest::get(origin_url)
.await?
.bytes()
.await?
.into_iter()
.collect::<Vec<u8>>();
let _ = self
.get_repo()
.create_file(path, format!("Add {}", name), content)
.branch(branch)
... | Rust | 0 |
#
#Escreva um módulo em python para tratar algumas strings e que possua as seguintes funcionalidades:
#Inverter uma string de trás pra frente.
#Retornar apenas letras com índice par.
#Retornar apenas letras com índice ímpar.
def reverse_text(text=""):
return text[::-1]
def even_letters(text=""):
return text[::2]
... | Python | 1 |
#!/usr/bin/env python
# encoding: utf-8
import cv2 as cv
import mediapipe as mp
import time
def _text_with_background(img, text, font=cv.FONT_HERSHEY_COMPLEX, fontScale=1.0, textPos=(10,10), textThickness=1,textColor=(0,255,0), bgColor=(0,0,0), pad_x=3, pad_y=3, bgOpacity=0.5):
(t_w, t_h), _= cv.getTextSize(text,... | Python | 1 |
y_threshold=self.config["retriever"]["similarity_threshold"]
)
else: # 默认使用向量检索器
self.retriever = VectorRetriever(
embedding_model=self.embedding_model,
vector_store=self.vector_store,
similarity_threshold=self.config["retriever"]["similar... | Python | 1 |
Send + Sync + 'static,
{
self.context(msg).context(kind).into()
}
}
<filename>src/parser/html.rs<gh_stars>1-10
use super::IResult;
use crate::ast::*;
use crate::parser::general::{
document_node, dynamic_context, DynamicChildParser, GenericChildParser, Input,
};
use crate::parser::twig::{twig_commen... | Rust | 0 |
from pydantic import BaseModel
class LiteUser(BaseModel):
username: str
disabled: bool
id_role: str | Python | 1 |
from yandex_music import Title
class TestTitle:
title = 'Hammasi'
full_title = 'Barcha janrlar musiqasi'
def test_expected_values(self, title):
assert title.title == self.title
assert title.full_title == self.full_title
def test_de_json_none(self, client):
assert Title.de_jso... | Python | 1 |
st(dice_scores, bins=30, alpha=0.7, color='blue')
axes[0, 0].axvline(dice_scores.mean(), color='red', linestyle='--',
label=f'Mean: {dice_scores.mean():.3f}')
axes[0, 0].set_title('Dice Score Distribution')
axes[0, 0].set_xlabel('Dice Score')
axes[0, 0].set_ylabel('Frequency')
... | Python | 1 |
"""
Write a function that takes in two tuples and performs mathematical division operation element-wise across the given tuples.
assert division_elements((10, 4, 6, 9),(5, 2, 3, 3)) == (2, 2, 2, 3)
"""
def division_elements(tuple1, tuple2):
"""
:param tuple1: tuple
:param tuple2: tuple
:return: tuple
... | Python | 1 |
from crud_database import *
from welcome_message import welcome_message
from pollen_daily_forecast import get_user_dependant_info, get_info_database
from smsmessage import *
import sys
USERS_DATA = get_info_database()
def show_options_for_user():
print()
print("""\u001b[36mIf you are a new subscriber please... | Python | 1 |
from m2cgen.assemblers import get_assembler_cls
from m2cgen.interpreters import RubyInterpreter
from tests import utils
from tests.e2e.executors.base import BaseExecutor
EXECUTOR_CODE_TPL = """
input_array = ARGV.map(&:to_f)
{model_code}
res = score(input_array)
{print_code}
"""
PRINT_SCALAR = """
puts res
"""
P... | Python | 1 |
from sqlalchemy import Column, String , Text
from sqlalchemy.ext.declarative import declarative_base
# Base class for SQLAlchemy models
Base = declarative_base()
class FileRecord(Base):
"""
Table to store uploaded file metadata.
Each row represents one unique file (by hash).
"""
__tablename__ = "f... | Python | 1 |
import sqlite3
conn = sqlite3.connect('spider.sqlite')
cur = conn.cursor()
cur.execute('''UPDATE Pages SET new_rank=1.0, old_rank=0.0''')
conn.commit()
cur.close()
print("All pages set to a rank of 1.0")
| Python | 1 |
ないので5秒待つ
std::thread::sleep(std::time::Duration::from_millis(5000 as u64));
}
do_stabilize_once_ftable_at_all_node();
}else{
std::thread::sleep(std::time::Duration::from_millis(100 as u64));
}
}
}
/*
def stabilize_th... | Rust | 0 |
of the [Perfdata]
pub fn value(&self) -> Option<Value> {
match self.unit {
Unit::None(v) => Some(v),
Unit::Percentage(v) => Some(v),
Unit::Seconds(v) => Some(v),
Unit::Bytes(v) => Some(v),
Unit::Counter(v) => Some(v),
Unit::Undetermine... | Rust | 0 |
f list of int): 32x16 的列表,表示每层16个专家所属的组索引。
"""
global similarity_group
num_layers = len(frequency_list)
num_experts = len(frequency_list[0]) # 每层有60个专家
print(num_experts)
group = [[-1 for _ in range(num_experts)] for _ in range(num_layers)] # 初始化组标签
limit = num_experts # 组的最大数量
accumu... | Python | 1 |
float32x4_t; 12],
) -> [float32x4_t; 12] {
// Algorithm: 4x3 good-thomas
// Size-4 FFTs down the columns of our reordered array
let mid0 = self
.bf4
.perform_parallel_fft_direct(values[0], values[3], values[6], values[9]);
let mid1 = self
.bf4
... | Rust | 0 |
ogenous transformation matrix descirbing the plane frmae with respect to the world frame
"""
w_T_plane = np.eye(4)
plane_axis = norm_vector(plane_axis) # unit vector
plane_x_axis_w = project_vector_to_plane(plane_x_axis, plane_axis, normalize=True) # coordinates of the x_axis of the plane coordinates e... | Python | 1 |
lect * from dual",
"with t as (select 1) select * from t",
"(with t as (select 1) select * from t",
"(((with t as (select 1) select * from t",
" with t as (select 1) select * from t",
" with t as (select 1) select * from t",
"( ( ( with t as (select 1) select * from t",... | Python | 1 |
stage_dilations.append(dilation)
cfg['stride'] = stage_strides
cfg['dilation'] = stage_dilations
cfg['first_dilation'] = stage_first_dilations
stage_args = [
dict(zip(cfg.keys(), values)) for values in zip(*cfg.values())
]
return stage_args
class CSPNet(nn.Layer):
def __in... | Python | 1 |
ource("/api/errors/recognition")
.to(kodi_helper::api::errors::get_recognition_errors_list),
)
.service(
web::resource("/api/errors/missing")
.to(kodi_helper::api::errors::get_unrecognized_movies),
)
// UI
... | Rust | 0 |
h = np.dot(hkl, self.reciprocal_lattice)
return np.sqrt(np.dot(Kh, Kh))
def loss(datath, datatar, match_tol=2, minimized_loss=False):
"""
Parameters
----------
datath : {angle_list,height_list} calculated according to the theory.
datatar : {angle_list,height_list} target.
match_tol : t... | Python | 1 |
sellationError> {
let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new();
let mut vertex_builder = simple_builder(&mut buffers);
let mut tessellator = FillTessellator::new();
let options = FillOptions::default();
let mut path_builder = Path::builder();
let mut last: Option<geo::Poin... | Rust | 0 |
{
test.arg("--no-run");
}
if self.no_fail_fast {
test.arg("--no-fail-fast");
}
if let Some(test_name) = self.test_name.as_ref() {
test.arg(test_name);
}
if !self.args.is_empty() {
test.arg("--");
test.args(&self... | Rust | 0 |
import logging
import time
from actions.base import ActionConfig, ActionConnector
from actions.move.interface import MoveInput
class MoveUnitreeSDKConnector(ActionConnector[MoveInput]):
def __init__(self, config: ActionConfig):
super().__init__(config)
async def connect(self, output_interface: Move... | Python | 1 |
&mut fmt::Formatter<'_>) -> fmt::Result {
match self.index() {
Some(a) => write!(f, "{}", a),
None => write!(f, "."),
}
}
}
custom_derive! {
/// Genotype representation as a vector of `GenotypeAllele`.
#[derive(NewtypeDeref, Debug, Clone, PartialEq, Eq, Hash)]
p... | Rust | 0 |
_inspector);
} else {
panic!("Wrong event type");
}
}
// ---- DDC node managers ----
#[ink::test]
fn add_and_remove_ddn_manager_works() {
let mut contract = make_contract();
let accounts = get_accounts();
let account = accounts.alice;
assert!(!contract.is_ddn_manager(account));
con... | Rust | 0 |
lf {
PMUXOR::A => 0,
PMUXOR::B => 1,
PMUXOR::C => 2,
PMUXOR::D => 3,
PMUXOR::E => 4,
PMUXOR::F => 5,
PMUXOR::G => 6,
PMUXOR::H => 7,
PMUXOR::_Reserved(bits) => bits,
... | Rust | 0 |
'default_positions': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
'joint_names': joint_names
}]
)
)
else:
raise Exception(f'Demo {demo} doesnt exist in yml')
else:
print(f"... | Python | 1 |
rgs.out_dir)
network = bn_absorber_weights(args.model, args.weights) # merge bn layer into conv kernel
msg_proto = bn_absorber_prototxt(args.model) # remove bn layer from prototxt file
# save prototxt for inference
print "Saving inference prototxt file..."
path = os.path.join(args.out_dir, "bn_c... | Python | 1 |
e_events_np_files(extract_root: str, events_np_root: str):
'''
:param extract_root: Root directory path which saves extracted files from downloaded files
:type extract_root: str
:param events_np_root: Root directory path which saves events files in the ``npz`` format
:type events... | Python | 1 |
import time
from synthetic_data import classification_data, multi_label_sequence_data, sequence_data
from tabulate import tabulate
from finetune import Classifier, SequenceLabeler
from finetune.base_models import RoBERTa
def benchmark(model_cls, config, x, y, runs):
train_time = 0
inference_time = 0
for... | Python | 1 |
# Copyright 2009-2011 Ram Rachum.
# This program is distributed under the LGPL2.1 license.
'''Testing module for `garlicsim.general_misc.sequence_tools.combinations`.'''
import nose.tools
from garlicsim.general_misc.sequence_tools import combinations
from garlicsim.general_misc import sequence_tools
def test():
... | Python | 1 |
import os
import cv2
import numpy as np
import torch
from ..helper import (
norm_img,
get_cache_path_by_url,
load_jit_model,
download_model,
)
from ..schema import InpaintRequest
from .base import InpaintModel
LAMA_MODEL_URL = os.environ.get(
"LAMA_MODEL_URL",
"https://github.com/Sanster/mode... | Python | 1 |
oint::ProgramResult, msg, program_error::ProgramError,
pubkey::Pubkey,
};
/// Processes an instruction
pub fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
input: &[u8],
) -> ProgramResult {
let instruction = GovernanceInstruction::try_from_slice(input)
.map_err(|_| Pr... | Rust | 0 |
x=int(input("Enter the number:"))
if x%2==0:
print("NUm is Even")
else:
print("Num is Odd") | Python | 1 |
, s], 1)
# top prpj and bot proj
top_feat = self.top_proj(s)
# mid_feat = self.mid_proj(m)
# bot_feat = self.bot_proj(l)
return [top_feat, top_feat, top_feat]
class AdaptiveFeatureSelection(nn.Module):
''' AdaptiveFeatureSelection '''
def __init__(self, down_num,down_in... | Python | 1 |
from typing import List, Optional
class SolutionFailed:
# 此为翻车版本,我注意力起飞了导致的
# 根本跑不通
# 勿看
# 请直接看下方 Solution 类
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
# 一些斜向访问用的工具函数
height = len(matrix)
width = len(matrix[0])
def diagonal_count_rows() ... | Python | 1 |
ū"),
('𧆼', "zhōng,dōng"),
('𧇄', "lú"),
('𧇈', "zù"),
('𧇌', "tóng"),
('𧇍', "xiā"),
('𧇎', "hé"),
('𧇓', "yuè"),
('𧇙', "nán"),
('𧇚', "bó"),
('𧇛', "hū"),
('𧇜', "qì"),
('𧇝', "shú"),
('𧇞', "qiāng"),
('𧇟', "zhōu"),
('𧇠', "yào"),
('𧇡', "gū"),
('�... | Rust | 0 |
est'.",
"locations": [(4, 42)],
},
],
schema,
)
def unknown_arg_on_directive_used_in_schema_extension():
schema = build_schema(
"""
directive @test(arg: String) on OBJECT
... | Python | 1 |
n from_str(s: &str) -> Result<Self> {
parse_api_versions(s.as_bytes()).to_result().map_err(|err| err.into())
}
}
named!(
parse_api_versions<ApiVersions>,
alt_complete!(
tag!("0.8.0") => { |_| ApiVersions::KAFKA_0_8_0 } |
tag!("0.8.1") => { |_| ApiVersions::KAFKA_0_8_1 } ... | Rust | 0 |
形狀:", y_train.shape)
client_str = "client3"
print("使用 train_half3 進行訓練")
print("use file", split_file)
return x_train, y_train,client_str
# for do one hot
def ChooseTrainDatastes(filepath, my_command,Choose_method):
# 加载选择的数据集
if my_command == 'total_train':
if (Choose_me... | Python | 1 |
feature = "zu")]
crate::Annotation {
lang: "zu",
tts: Some("ichime yomoya"),
keywords: &["ichime", "ichime yomoya", "insimbi", "umbungazo", "umoya"],
},
],
};
#[doc = "🎑"]
pub const MOON_VIEWING_CEREMONY: crate::Emoji = crate::Emoji {
glyph: "🎑",
codepoi... | Rust | 0 |
let json: Value = serde_json::from_str(&json_string)
.expect("Could not parse GitHub response as JSON.");
json["tag_name"]
.clone()
... | Rust | 0 |
fig, ax = plt.subplots()
splits = vpr_ds.get_image_paths()[qi_ds].split("/")[-2:]
f_title = str(os.path.join(*splits))
# ax.set_title(f_title)
_i = str(largs.qu_indices[i])
if largs.qu_in_db:
ax.set_title(f"Layer: {l} - Image: {_i} (DB)",
... | Python | 1 |
# Copyright 2025 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
from datetime import datetime
from typing import Union
from pydantic import Field
from pydantic.networks import IPvAnyAddress
from maascommon.enums.ipranges import IPRangeType
fr... | Python | 1 |
d the FoundationDB project authors.
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to ... | Rust | 0 |
defines += i.split()
find_define = re.findall("([A-Z_0-9 ]+).*:", r, re.I | re.M)
if find_define:
for i in find_define:
defines += i.split()
for d in defaults, default_directories:
for s in d:
if s not in defines:
r += "\r\n" + s + " EQU %s" % d[s]
... | Python | 1 |
value is 3.
@param report_vad
- true: Enable the voice activity detection of the local user. Once it is enabled, the `vad` parameter of the `onAudioVolumeIndication` callback reports the voice activity status of the local user.
- false: (Default) Disable the voice activity detection of the local user. ... | Rust | 0 |
from srcp.utils.input import get_data
data: list[tuple[str, int]] = [(n.split(" ")[0], int(n.split(" ")[1])) for n in get_data(day=2, year=2021).splitlines()]
result_1 = {
'horizontal': 0,
'vertical': 0
}
def part_1(result: dict[str, int]) -> dict[str, int]:
for n in data:
if n[0] == 'forward':
... | Python | 1 |
2 * total_payout_1 / 3;
// if cfg!(feature = "equalize") {
// // TODO: fix equalize
// // // Nominator 2: has [400 / 2000 ~ 1 / 5 from 10] + [600 / 2000 ~ 3 / 10 from 20]'s reward.
// // assert_eq_error_rate!(
// // Ring::total_balance(&2),
// // initial_balance + payout_for_10 / 5 + payout_fo... | Rust | 0 |
r
def database_id(self, database_id):
"""
Sets the database_id of this DataguardMetrics.
The database ID of the Managed Database. Every database had its own ID and that value is captured here.
:param database_id: The database_id of this DataguardMetrics.
:type: str
... | Python | 1 |
next);
if next.is_empty() && workers.all_idle() {
break;
}
for worker in workers.available() {
let next_step = match next.pop() {
None => break,
Some(next_step) => next_step,
};
assigned.insert(next_step);
... | Rust | 0 |
n = len(points)
midpoint = n // 2
left_half = points[:midpoint]
right_half = points[midpoint:]
# Recursive calls with logarithmic time complexity
self.logarithmic_algorithm(left_half)
self.logarithmic_algorithm(right_half)
# ... (additional hypothetical ... | Python | 1 |
from . import *
import os
from flask import abort, redirect, send_from_directory
from mod.auth import require_auth_decorator
@app.route('/')
def redirect_to_welcome():
"""
重定向至/src,显示主页
:return:
"""
return redirect('/src')
@app.route('/acknowledgments')
@app.route('/acknowledgments.html')
def... | Python | 1 |
d_shuffle = tf.train.shuffle_batch(
[self.images["valid_original"], self.labels["valid_original"]],
batch_size=self.batch_size,
capacity=25000,
enqueue_many=True,
min_after_dequeue=0,
num_threads=16,
seed=self.seed,
allow_smaller_final_batch=True,
)
... | Python | 1 |
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import TYPE_CHECKING
from .base_env_window import BaseEnvWindow
if TYPE_CHECKING:
from ..rl_task_env import RLTaskEnv
class RLTaskEnvWindow(B... | Python | 1 |
import os
import subprocess
from cli.src.Config import Config
from cli.src.Log import Log, LogPipe
terraform_verbosity = ['ERROR','WARN','INFO','DEBUG','TRACE']
class TerraformCommand:
def __init__(self, working_directory=os.path.dirname(__file__)):
self.logger = Log(__name__)
self.APPLY_COMMAND... | Python | 1 |
insert(
"noshowcancelled",
(TokenKind::Keyword(Keyword::Noshowcancelled), 2),
);
m.insert(
"pulsestyle_ondetect",
(TokenKind::Keyword(Keyword::PulsestyleOndetect), 2),
);
m.insert(
"pulsestyle_onevent",
(TokenKind::Keyword(Keyword::PulsestyleOnevent), 2),
... | Rust | 0 |
s: Vec<* mut World>,
access: AccessMap,
jobs: Vec<Job>,
}
pub struct FrameBuilder {
state: RefCell<State>,
pool: jobs::Pool,
access_history: HashMap<ResourceId, AccessPattern>,
}
impl FrameBuilder {
pub fn new(scope: &Scope) -> Self {
FrameBuilder {
state: RefCell::new(Stat... | Rust | 0 |
"""
Counting Splatfacto Config
Define your custom method here that registers with Nerfstudio CLI.
"""
from __future__ import annotations
# from counting_splatfacto.counting_datamanager import (
# CountingDataManagerConfig, hopefully here I can use the normal one?
# )
from nerfstudio.data.datamanagers.full_images_... | Python | 1 |
�則負け
Foul(Teban,FoulKind),
/// 時間切れ負け
Timeover(Teban),
}
/// 対局の勝敗
#[derive(Clone, Copy, Eq, PartialOrd, PartialEq, Debug)]
pub enum GameEndState {
/// 勝ち
Win,
/// 負け
Lose,
/// 引き分け
Draw,
}
/// 自己対局時の反則負けの種類
#[derive(Clone, Copy, Eq, PartialOrd, PartialEq, Debug)]
pub enum FoulKind {
/// 合法手... | Rust | 0 |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from core.views import AirportViewSet, AirlineViewSet, RunwayViewSet, FlightViewSet
router = DefaultRouter()
router.register(r'airport', AirportViewSet)
router.register(r'airline', AirlineViewSet)
router.register(r'runway', RunwayVi... | Python | 1 |
CouplingBuckets::new(config, ×tamps, bucketing_config);
let foo_coupling = coupling_buckets.file_coupling_data(rc_pb("foo"));
assert_eq!(foo_coupling.buckets.len(), 1);
let foo_coupling = &foo_coupling.buckets[0];
assert_eq!(foo_coupling.activity_bursts, 4);
assert_eq!(
... | Rust | 0 |
py as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv1D, Flatten, Dropout, MaxPooling1D
from tensorflow.keras.optimizers import Adam
# Reshape data for CNN input
X_train_reshaped = np.expand_dims(x_train, axis=2)
X_test_r... | Python | 1 |
up signal handler for USR1
// * Launch Xwayland with USR1 ignored so Xwayland will signal us when it is ready (also redirect
// Xwayland's STDOUT to STDERR so its output, if any, won't distract us)
// * Print "S" and exit if USR1 is received
command.arg("-c").arg(format!(
"trap 'echo S' USR1;... | Rust | 0 |
[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(transparent)]
pub struct Values {
#[serde(flatten)]
inner: HashMap<String, String>,
}
impl Values {
pub fn new() -> Self {
Values {
inner: HashMap::new(),
}
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &str)>... | Rust | 0 |
true;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) != 0
};
PERI_SPI0_ENR { bits }
}
#[doc = "Bit 2"]
#[inline]
pub fn peri_uart2_en(&self) -> PERI_UART2_ENR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = ... | Rust | 0 |
d-4",
},
});
assert_eq!(serde_json::to_value(not).unwrap(), json);
}
#[test]
fn config_changed() {
let not = Notification::ConfigChanged {
view_id: ViewId(String::from("view-id-2")),
changes: ConfigChanges {
other: {
... | Rust | 0 |
st_sol_file, "w") as f:
json.dump(prob_inst_sol_data, f, indent=4)
print(f"Saved {prob_inst_sol_file}")
prob_inst_data["file_name"] = prob_inst_sol_file
saved_files.append(prob_inst_sol_file)
return saved_files
def validate_solution_files(json_solution_schema_url, prob_inst_... | Python | 1 |
.values(&beatmap_clone)
.execute(conn)
{
Ok(_) => (),
Err(err) => println!("Error while attempting to insert beatmap into beatmap cache: {:?}", err),
}
});
Ok(Some(beatmap))
}
/// Returns a user's current stats for a g... | Rust | 0 |
urn self.shared
def set_input_embeddings(self, new_embeddings):
self.shared = new_embeddings
self.encoder.set_input_embeddings(new_embeddings)
def get_encoder(self):
return self.encoder
def _prune_heads(self, heads_to_prune):
"""
Prunes heads of the model. heads_to... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.