text string | label_name string | labels int64 |
|---|---|---|
import os
import pickle
from imageio import imwrite
import numpy as np
def _make_missing_directories(file_path):
directory_path = os.path.dirname(file_path)
os.makedirs(directory_path, exist_ok=True)
def _save_pgm(np_array,pgm_path):
np_array_uint8 = np.uint8(np_array)
_make_missing_directories(pgm_p... | Python | 1 |
import json
import re
def remove_not(x):
match_number = re.compile('[\$]?\ *10\^[{]?\ *-?[0-9]+\ *[}]?\ *[\$]?')
result=re.findall(match_number, x)
if len(result) !=0:
return re.split(match_number, x)[-1]
return None
def parse_not(inputs):
try:
if not inputs:
return '','... | Python | 1 |
n enumerate(derivation_steps):
latex_lines.append(f" \\item {step['description']}")
latex_lines.append("\\end{enumerate}")
latex_lines.append("")
# Add computed results
if computed_values:
latex_lines.extend([
"\\textbf{Computed Res... | Python | 1 |
#!/usr/bin/env python3
import graphviz
import kaldifst
s1 = """
0 1 a 0.1
0 2 b 0.1
1 3 c 0.4
1 3 d 0.2
2 3 c 0.3
2 3 d 0.2
3 0
"""
sym1 = kaldifst.SymbolTable(name="sym1")
sym1.add_symbol("eps", 0)
sym1.add_symbol("a", 1)
sym1.add_symbol("b", 2)
sym1.add_symbol("c", 3)
sym1.add_symbol("d", 4)
a = kaldifst.compile... | Python | 1 |
satty', return_value=True)
self.tty_stdout_patcher.start()
cli = VaultCLI(args=['ansible-vault', 'create', '/dev/null/foo'])
cli.parse()
cli.run()
self.tty_stdout_patcher.stop()
@patch('ansible.cli.vault.VaultCLI.setup_vault_secrets')
@patch('ansible.cli.vault.VaultEdito... | Python | 1 |
'wid': width_mult_setting,
'ks': ks_setting,
'e': expand_setting,
'd': depth_setting,
}
def get_active_subnet(self, preserve_weight=True):
def get_or_copy_subnet(m, **kwargs):
if hasattr(m, 'get_active_subnet'):
out = m.get_activ... | Python | 1 |
method = 'PhyDNet'
# model
patch_size = 4
# training
# lr = 1e-4
batch_size = 4 # 4 x bs4 = bs16
sched = 'cosine'
warmup_epoch = 0 | Python | 1 |
int(_canvas.height * y_percent / 100 - _layer.height / 2)
# composit layer
_comp = copy.copy(_canvas)
_compmask = Image.new("RGB", _comp.size, color='black')
_comp.paste(_layer, (x, y))
_compmask.paste(_mask, (x, y))
_compmask = _compmask.convert... | Python | 1 |
default=3,
help='Delay'
)
@click.option(
'--iterations',
default=5,
help='Iterations of WPE'
)
def main(channels, sampling_rate, file_template, taps_frequency_dependent,
delay, iterations):
"""
User interface for WPE. The defaults of the command line interface are
suited for examp... | Python | 1 |
Options {
//! pass_romaji: true,
//! ..Default::default()
//! }
//! ),
//! "only カナ"
//! );
//! assert_eq!(to_katakana("wi"), "ウィ");
//! assert_eq!(to_katakana_with_opt("wi", Options {use_obsolete_kana: true, ..Default::default() }),"ヰ");
//! ```
use is_romaji::*;
use is_mix... | Rust | 0 |
ted a ciel workspace here.");
info!("Please run `ciel farewell` to nuke it before running this command.");
return Err(anyhow!("Unable to create a ciel workspace."));
}
info!("Before continuing, I need to ask you a few questions:");
let config = config::ask_for_config(None)?;
let mut init... | Rust | 0 |
modified, most_recent_path))
}
// Generated by `scripts/generate.js`
pub type VkPhysicalDeviceScalarBlockLayoutFeatures = super::super::vk::VkPhysicalDeviceScalarBlockLayoutFeatures;
#[doc(hidden)]
pub type RawVkPhysicalDeviceScalarBlockLayoutFeatures = super::super::vk::RawVkPhysicalDeviceScalarBlockLayoutFeatures;u... | Rust | 0 |
'a>;
type Error = Error;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
where
T: Serialize,
{
self.vec.add(to_object(self.enc, &value)?)?;
Ok(())
}
fn end(self) -> Result<JObject<'a>> {
variant_map(self.enc, &self.name, self.vec.to_vector()?)
... | Rust | 0 |
roU32) -> &mut Self {
self.level_group_size = NonZeroU32::new(cmp::max(value.get(), 2)).unwrap();
self
}
pub fn min_level_size(&mut self, value: NonZeroU32) -> &mut Self {
self.min_level_size = value;
self
}
#[logging_timer::time("WordsLevelPositions::{}")]
pub fn e... | Rust | 0 |
source in enumerate(message["sources"]):
st.markdown(f"**Source {i+1}:** {source['title']}")
st.markdown(f"**URL:** [{source['url']}]({source['url']})")
st.markdown(f"**Provider:** {source['source']}")
st.markdown("---")
... | Python | 1 |
"""Definitions for go-eCharger buttons exposed via MQTT."""
from __future__ import annotations
from dataclasses import dataclass
import logging
from homeassistant.components.button import ButtonEntityDescription
from homeassistant.helpers.entity import EntityCategory
from . import GoEChargerEntityDescription
_LOGGE... | Python | 1 |
d:{RESET} {random_string}")
time_to_crack(random_string, CHARACTER_SET_SIZE, ATTEMPTS_PER_SECOND)
good_passwords.append(random_string)
else:
print(f"{RED}Option {i} not recommended:{RESET} {random_string}")
if len(good_passwords) > 0:
while True:
sel... | Python | 1 |
&ArrayBase<S1, Ix2>, n: usize, m: usize) -> ArrayBase<S2, Ix2>
where
A: Copy + Zero,
S1: Data<Elem = A>,
S2: DataMut<Elem = A> + DataOwned,
{
let av = a.slice(s![..n, ..m]);
let mut a = replicate(&av);
Zip::indexed(&mut a).for_each(|(i, j), elt| {
if i > j {
*elt = A::zero()... | Rust | 0 |
t precise
img_list = draw_traj(img_list, traj, vis=viss, length=5, thickness=2, color=(0, 255, 0))
# traj_gts = np.genfromtxt(f'{cfg.eval_dataset_path}/gt_tracks/{seq}_occ.gt.txt')
# for traj_id in traj_ids:
# traj_gt = traj_gts[traj_gts[..., 0] == traj_id]
# x_interp = interp1d(
#... | Python | 1 |
child)?;
let child = compositor.create_sprite_visual()?;
child.set_offset(Vector3 {
x: 3.0,
y: 0.0,
z: 0.0,
})?;
children.insert_at_bottom(child)?;
assert!(children.count()? == 3);
// TODO: Collection iteration is still crude but at least the underlying collection inte... | Rust | 0 |
ModuleKind::Legacy => {
let app = create_state(jig_id, module_id).await;
render_page_body(app.clone());
*state.app.borrow_mut() = Some(app);
}
... | Rust | 0 |
) as u8 },
);
}
#[test] //FIXME: #[simd_test(enable = "neon")]
fn test_vhsub_u16() {
test_ari_u16(
|i, j| unsafe { vhsub_u16(i, j) },
|a: u16, b: u16| -> u16 { (((a as u16) - (b as u16)) / 2) as u16 },
);
}
#[test] //FIXME: #[simd_test(enable = "neon")]
fn test_vhsubq_u16() {
testq_ari_u... | Rust | 0 |
nstancesRequest(self, messages, igm_ref, args):
request = messages.ComputeRegionInstanceGroupManagersDeleteInstancesRequest(
instanceGroupManager=igm_ref.Name(),
regionInstanceGroupManagersDeleteInstancesRequest=messages
.RegionInstanceGroupManagersDeleteInstancesRequest(instances=[]),
... | Python | 1 |
SubmitClientCommandAndWaitStatus(self.handle, command);
let status_type = ffi::b3GetStatusType(status_handle);
if status_type != CMD_SYNC_BODY_INFO_COMPLETED as i32 {
return Err(Error::new("Error in sync_body_info command"));
}
}
Ok(())
}
/// c... | Rust | 0 |
up for ego policy
self.ego_policy.clean_up()
# clean up for CBV policy
self.cbv_policy.clean_up()
# stop sensor objects
for e_i in range(self.num_scenario):
self.env_list[e_i].clean_up()
if self.statistics_manager is not None:
self.statistics_ma... | Python | 1 |
# Copyright (c) 2025, Brit and Contributors
# See license.txt
# import frappe
from frappe.tests.utils import FrappeTestCase
class TestEventMethod(FrappeTestCase):
pass
| Python | 1 |
"""Tests for the 'Forgot Password' functionality on the My Account page.
Covers both invalid and registered email scenarios.
Fixtures:
init_driver : Sets up the WebDriver.
go_to_my_acct : Navigates to My Account page before tests.
"""
import pytest
from demostore_automation.conftest import init_driver
fro... | Python | 1 |
# Задача 3. Индекс массы тела
# Алексей работает диетологом в частной клинике,
# каждый день он принимает пациентов разных возрастов и с
# разными показателями роста (в метрах) и веса (в кг).
# Для каждого человека ему нужно считать индекс массы тела -
# это вес поделить на рост в квадрате. По государственным
# стандар... | Python | 1 |
v = c;
}
} else {
header_string.push_str(key.as_str());
}
header_string.push_str(": ");
match value.to_str() {
Ok(value) => header_string.push_str(value),
Err(_) => header_string.push_str(&format!("{:?}", val... | Rust | 0 |
}
pub fn load(self) -> EntryPoint {
// TODO: This requires the target page table can access the elf input.
let file_base = self
.page_table
.translate_addr(VirtAddr::from_ptr(self.elf.input.as_ptr()))
.expect("failed to translate file base");
assert!(... | Rust | 0 |
_to_duration(seconds: f64) -> Duration {
let whole_seconds = seconds.trunc() as u64;
let nanos = seconds.fract() * 1_000_000_000f64;
Duration::new(whole_seconds, nanos as u32)
}
#[test]
fn double_seconds_to_duration_whole_second() {
let dur = double_seconds_to_duration(1.0);
assert_eq!(dur.as_secs(... | Rust | 0 |
(rguard);
WaitQueue::wait(wguard, || {});
// Another thread has passed the lock to us
} else {
// We are just now obtaining the lock
*wguard.lock_var_mut() = true;
}
}
#[inline]
pub unsafe fn try_write(&self) -> bool {
let rguard = try_loc... | Rust | 0 |
bypass {
// Wait for lock
while self.prci.core_pllcfg.read().plllock().bit_is_clear() {}
// Select corepll
self.prci.corepllsel.modify(|_, w| w.source().corepll());
}
if coreclk != HFXCLK {
// Select PLL as a core clock source
sel... | Rust | 0 |
import torch
import numpy as np
from .yhj_utils import part_random_retrieve, part_class_balance_random_retrieve, part_random_retrieve_features, part_class_balance_random_features_retrieve
"""
retrieve samples
"""
class Part_lt_balance_retrieve(object):
def __init__(self, params):
super().__init__()
... | Python | 1 |
# Copyright (C) 2020 Adek Maulana
#
# SPDX-License-Identifier: GPL-3.0-or-later
# This program 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 version 3 of the License, or
# (at your option) any later v... | Python | 1 |
payload: "!".to_string(),
},
it.next().unwrap().unwrap(),
);
assert!(it.next().unwrap().is_none());
}
#[test]
fn test_notifications_next_block() {
let conn = or_panic!(Connection::connect(
"postgres://postgres@localhost:5433",
TlsMode::None,
));
or_panic... | Rust | 0 |
ings
def get_static_strings_from_rdata(sample, static_strings) -> List[StaticString]:
pe = pefile.PE(data=pathlib.Path(sample).read_bytes(), fast_load=True)
try:
rdata_section = get_rdata_section(pe)
except ValueError:
return []
start_rdata = rdata_section.PointerToRawData
end_rd... | Python | 1 |
agic datapoints (words, card values, etc). Catalog
//! objects are provided by the API as aids for building other Magic software and understanding
//! possible values for a field on Card objects.
//!
//! Visit the oficial [docs](https://scryfall.com/docs/api/catalogs) for more documentation.
use serde::{Deserialize, S... | Rust | 0 |
id_info.get('videoDetails', {}).get('keywords', [])
@property
def channel_id(self) -> str:
"""Get the video poster's channel id.
:rtype: str
"""
return self.vid_info.get('videoDetails', {}).get('channelId', None)
@property
def channel_url(self) -> str:
"""Const... | Python | 1 |
''' Exercício - Lista de tarefas com desfazer e refazer
Música para codar =) Everybody wants to rule the world - Tears for fears
todo = [] -> lista de tarefas
todo = ['fazer café'] -> Adicionar fazer café
todo = ['fazer café', 'caminhar'] -> Adicionar caminhar
desfazer = ['fazer café',] -> Refazer ['caminhar']
desfazer... | Python | 1 |
in::ABS,
1,
args.len(),
)),
}
}
fn sig<'s>(args: &[f64], lambda: &'s Lambda, scope: &mut Scope<'s>) -> Result<f64, EvalError> {
let (&start, &end) = match args {
[start, end] => (start, end),
_ => {
return Err(EvalError::arg_count_does_not_match(
... | Rust | 0 |
index of current keyboard map for passing to javascript
pub fn cur_map_index(ctx: &state::Context) -> i32 {
cur_map_enum(ctx) as i32
}
/// Return lookup table of current keyboard map for handling keystroke results
pub fn cur_map_lut(ctx: &state::Context) -> &'static MapResultLUT {
match cur_map_enum(ctx) {
... | Rust | 0 |
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
wgpu::ImageCopyTexture {
texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::ImageCopy... | Rust | 0 |
ng = mbstring1.clone();
mbstring.zero_out();
// `zero_out` sets the `len` to 0, here we reset it to check that the bytes were zeroed
#[cfg_attr(
any(test, feature = "pre"),
forward(impl pre::std::vec::Vec),
assure(
new_len <= self.capacity(),
... | Rust | 0 |
'''
Created on Mar 6, 2012
@package: superdesk user
@copyright: 2012 Sourcefabric o.p.s.
@license: http://www.gnu.org/licenses/gpl-3.0.txt
@author: Mihai Balaceanu
The API specifications for the user.
'''
from ally.api.config import service, query, UPDATE, call, model
from ally.api.criteria import AsLikeOrdered, AsD... | Python | 1 |
= "prediction":
# returns the model value at x
if x is None: # TODO: ensure if x is between lb and ub
raise RuntimeError("Cannot query model at location = None!")
mean, _var = server.strat.predict(
server._config_to_tensor(x),
probability_space=probability_s... | Python | 1 |
c<Agent<'a>>) -> Option<f64> {
let mut buys = Vec::<&'a mut Agent<'a>>::new();
let mut sells = Vec::<&'a mut Agent<'a>>::new();
agents.iter_mut().for_each(|a| if a.buyer { &mut buys } else { &mut sells }.push(a));
buys.sort_unstable_by(|a, b| a.cmp(b).reverse());
sells.sort_unstable_by(|a, b| a.cmp(... | Rust | 0 |
ttack = OptimizationAttack(environment, start_state, eps, num_iter, step_size, time_horizon, maxlen, net_type3, "time")
#PPO_attack.generate(num_traj=10)
#PPO_attack.save_attack("Adv_Traj/Ant_PPO_Time")
#ATLA_attack.generate(num_traj=10)
#ATLA_attack.save_attack("Adv_Traj/Ant_ATLA_Time")
#LSTM_attack.generate(num_tr... | Python | 1 |
def habitat_predict(session):
print('analysis: running deepview_predict()')
yield session.habitat_predict()
release_memory()
| Python | 1 |
: ::AudioFormat = ::AudioFormat::S18be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_U18: ::AudioFormat = ::AudioFormat::U18be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_F32: ::AudioFormat = ::AudioFormat::F32be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_F64: ::AudioFormat = ::AudioFormat:... | Rust | 0 |
,
}
}
};
($func_name:ident, $self:ty, $return:ty) => {
fallback_surface_impl!($func_name, $self, $return,);
};
($func_name:ident, $self:ty) => {
fallback_surface_impl!($func_name, $self, ());
};
}
macro_rules! fallback_surface_err_impl {
($func_name:ident, $se... | Rust | 0 |
import pytest
from flask_jwt_extended.utils import decode_token
from backend.app.models import Role, UserRole
from backend.app import db
def auth_header(token):
return {"Authorization": f"Bearer {token}"}
def register(client, creds):
if "password" in creds and "confirm_password" not in creds:
creds["con... | Python | 1 |
=0x20DC => Script::Inherited,
0x20DD..=0x20E0 => Script::Inherited,
0x20E1 => Script::Inherited,
0x20E2..=0x20E4 => Script::Inherited,
0x20E5..=0x20F0 => Script::Inherited,
0x302A..=0x302D => Script::Inherited,
0x3099..=0x309A => Script::Inherited,
0xFE00..=0xFE0F... | Rust | 0 |
use_database=False,
verbose=verbose
)
if filter_user and use_database:
memory = Memory(
embeddings_model=embeddings_model,
user_id=filter_user,
session_id="cli-session",
use_database... | Python | 1 |
e,
11 => LateralRaiseExerciseName::LeaningDumbbellLateralRaise,
12 => LateralRaiseExerciseName::LyingDumbbellRaise,
13 => LateralRaiseExerciseName::MuscleUp,
14 => LateralRaiseExerciseName::OneArmCableLateralRaise,
15 => LateralRaiseExercis... | Rust | 0 |
gap1+=(humaneval_scores[0]-humaneval_scores[1])/humaneval_scores[0]
else:
overall_gap1+=0
if humaneval_scores[2]!=0:
overall_gap2+=(humaneval_scores[2]-humaneval_scores[3])/humaneval_scores[2]
else:
overall_gap2+=0
if mbpp_scores[0]!=0:
overall_gap3+=(mbpp_scores[0]-mbpp_... | Python | 1 |
=404)
except User.DoesNotExist:
return JsonResponse({"message":"User does not exist"}, safe=False, status=400)
except json.decoder.JSONDecodeError:
return JsonResponse({"message":"Invalid body"}, safe=False, status=400)
if request.method == "DELETE":
... | Python | 1 |
a message that holds references to the other
let (wh_a, rh_a) = oak::channel_create().unwrap();
let (wh_b, rh_b) = oak::channel_create().unwrap();
oak::channel_write(wh_a, &data, &[wh_b.handle, rh_b.handle]).unwrap();
oak::channel_write(wh_b, &data, &[wh_a.handle, rh_a.handle]).unwrap();
// Keep th... | Rust | 0 |
fn bytes(&self) -> &[u8] {
&self.bytes
}
fn information_fields(&self) -> Vec<Field> {
vec![
Field::new(
"OBSS Scan Passive Dwell",
format!("{} TU", self.obss_scan_passive_dwell_tu()),
),
Field::new(
"OBSS ... | Rust | 0 |
=> {
buf.push(values_brush.paint(match progress.done_at {
Some(done_at) => format!("{}/{}", progress.step.load(Ordering::SeqCst), done_at),
None => format!("{}", progress.step.load(Ordering::SeqCst)),
}));
}
... | Rust | 0 |
) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or("not a controller")?;
let stash = &ledger.stash;
<Validators<T>>::remove(stash);
<Nominators<T>>::remove(stash);
}
fn set_payee(origin, payee: RewardDestination) {
let controller = ensure_signed(origin)?;
... | Rust | 0 |
import tensorflow as tf
import numpy as np
from matplotlib import pyplot as plt
# M: minibatch size
# n: number of items in each sequence
# s: scores
np.set_printoptions(precision=4, suppress=True)
eps = 1e-20
def bl_matmul(A, B):
return tf.einsum('mij,jk->mik', A, B)
def br_matmul(A, B):
return tf.einsum('ij,m... | Python | 1 |
::c_void;
}
extern "C" {
pub fn xmlMemStrdupLoc(
str: *const ::std::os::raw::c_char,
file: *const ::std::os::raw::c_char,
line: ::std::os::raw::c_int,
) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn xmlInitGlobals();
}
extern "C" {
pub fn xmlCleanupGlobals();
}
/// xmlParserInputBufferCreate... | Rust | 0 |
<T, V> IntoIterator for HConMap<T, V>
where
T: HashConsed,
T::Inner: Hash + Eq,
{
type Item = (HConsed<T::Inner>, V);
type IntoIter = ::std::collections::hash_map::IntoIter<HConsed<T::Inner>, V>;
fn into_iter(self) -> Self::IntoIter {
self.map.into_iter()
}
}
impl<T, V> ::std::iter::From... | Rust | 0 |
ile {}: {}", file.display(), error),
Error::Arguments(err) => write!(f, "{}", err),
Error::Environment(err) => write!(f, "{}", err),
Error::Validation(err) => write!(f, "Invalid configuration: {}", err),
}
}
}
impl ::std::fmt::Debug for Error {
fn fmt(&self, f: &mut ... | Rust | 0 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import streamlit as st
# Title of the app
st.title('Gravity Model for Trip Distribution')
# Input section for user-provided data
st.header('Input Data')
# Input Population (P)
st.subheader('Population in each zone')
P = []
f... | Python | 1 |
import torch
from torch.nn import Linear
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, GATConv, MessagePassing
import torch.nn as nn
from torch_geometric.utils import add_self_loops, degree
from torch_geometric.nn import SAGEConv,GCNConv
class GraphSAGE(nn.Module):
def __init__(self, inpu... | Python | 1 |
'#'),
5 => KeyboardKey::Printable('4', '$'),
6 => KeyboardKey::Printable('5', '%'),
7 => KeyboardKey::Printable('6', '^'),
8 => KeyboardKey::Printable('7', '&'),
9 => KeyboardKey::Printable('8', '*'),
10 => KeyboardKey::Printable('9', '('),
11 => KeyboardKey::Printable('0', ')'),
12 => KeyboardKey::Pri... | Rust | 0 |
cf].rooms[game.cr.y as usize][game.cr.x as usize]
.tiles[game.player.current_frame_tile.y as usize][game.player.current_frame_tile.x as usize].unlock();
game.player.has_key = false;
//Debug: println!("{}", game.cf);
// FLOOR CHANGING D... | Rust | 0 |
d::LedDriver<'static, LedLow<'static, stm32f412g::gpio::Pin<'static>>>,
button: &'static capsules::button::Button<'static, stm32f412g::gpio::Pin<'static>>,
alarm: &'static capsules::alarm::AlarmDriver<
'static,
VirtualMuxAlarm<'static, stm32f412g::tim2::Tim2<'static>>,
>,
gpio: &'static ... | Rust | 0 |
import heapq
import math
def a_star():
# Define the initial state of the city map as a 2D tuple
initial_state = ((18, 9, 2, 'x', 9, 14, 'x', 1, 'x'),
(3, 14, 18, 7, 'x', 3, 'x', 2, 19),
(6, 18, 20, 3, 13, 'x', 6, 10, 'x'),
(20, 'x', 12, 4, 14, 6, ... | Python | 1 |
},
{ 'baitname': '弓角', 'probability': ' 2%' },
{ 'baitname': '极地磷虾', 'probability': ' 2.9%' },
{ 'baitname': '巨型大蚊', 'probability': ' 0%' },
{ 'baitname': '海水万能饵', 'probability': ' 0.1%' }
],
'areas': ['东拉诺西亚-南鲜血滨', '东拉诺西亚-太阳海岸', '海雾村-海雾村']
},
'黑鬼鱼': {
'fish_id... | Python | 1 |
import logging
from fastapi import APIRouter, Depends, Request
from fastapi.responses import HTMLResponse
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from borgitory.models.database import (
Repository,
PruneConfig,
CloudSyncConfig,
NotificationConfig,
RepositoryChe... | Python | 1 |
import random
import time
import requests
import re
import chromadb
from chromadb.config import Settings
# Setup Chroma client and collection
client = chromadb.Client(Settings(chroma_db_impl="duckdb+parquet", persist_directory="./chroma"))
collection = client.get_or_create_collection(name="marketwatch")
def clean_whe... | Python | 1 |
(Register::IY),
if flags & 0b1000_0000 != 0 { 'S' } else { 's' },
if flags & 0b0100_0000 != 0 { 'Z' } else { 'z' },
if flags & 0b0001_0000 != 0 { 'H' } else { 'h' },
if flags & 0b0000_0100 != 0 { 'P' } else { 'p' },
if flags & 0b0000_0010 != 0 { 'N' } else { 'n' },
if fla... | Rust | 0 |
fix("RoleArn");
if let Some(var_4) = &input.role_arn {
scope_3.string(var_4);
}
#[allow(unused_mut)]
let mut scope_5 = writer.prefix("FeatureName");
if let Some(var_6) = &input.feature_name {
scope_5.string(var_6);
}
writer.finish();
Ok(aws_smithy_http::body::SdkBody::fro... | Rust | 0 |
import os
import torch
import random
from torchvision.utils import save_image
"""Basic backdoor attack
This version uses general backdoor trigger: blending a mark with a mask and a transparency `alpha`
i.e., img = img + alpha * self.trigger_mask * (self.trigger_mark - img)
"""
from utility import load_config
# 读入配置信息
... | Python | 1 |
clone());
}
}
if let Some(task) = new_task {
// There is a new task we want to switch to.
// Handle the current task.
if status == TaskStatus::TaskRunning {
// Mark the running task as ready again and add it back to the queue.
self.current_task.borrow_mut().status = TaskStatus::TaskReady;
... | Rust | 0 |
=self._build_failure_result_view_materialization(
node_id, nr_childs, threshold_childs, model_materialization
),
severity=get_severity(self.config, self.ALIAS, self.DEFAULT_SEVERITY),
)
)
elif nr_... | Python | 1 |
'''mcibi_deeplabv3_resnest101os8_cocostuff10k'''
import os
import copy
from .base_cfg import SEGMENTOR_CFG
from .._base_ import DATASET_CFG_COCOStuff10k_512x512, DATALOADER_CFG_BS32
# deepcopy
SEGMENTOR_CFG = copy.deepcopy(SEGMENTOR_CFG)
# modify dataset config
SEGMENTOR_CFG['dataset'] = DATASET_CFG_COCOStuff10k_512x... | Python | 1 |
,
a![
"Perfect",
attrs! {At::Class => "link", At::Href => "/archive/perfect/"}
],
br![],
a![
"Prime",
attrs! {At::Class => "link", At::Href => "/archive/prime/"}
],
],
]
}
<reponame>co... | Rust | 0 |
_effect: &Effect<<ARMv7 as Arch>::Address>,
_ctxs: &arm::v7::MergedContextTable
) -> Vec<(<ARMv7 as Arch>::Address, Update)> {
if instr.opcode == Opcode::BL {
event!(Level::ERROR, instr = ?instr, opcode = ?instr.opcode, "missing call destination stuff for {}", instr);
/*
vec!... | Rust | 0 |
{
result_to_int(
self.dijkstra
.remove_connection(source.into(), target.into(), bidirectional),
)
}
#[export]
/// Returns [true] if there is a connection from `source` to
/// `target` (and they both exist).
///
/// # Example
/// ```gdscript
/... | Rust | 0 |
o_json() on the object.
Args:
data: dict, A deserialized JSON object.
Returns:
An instance of a Credentials subclass.
"""
data = json.loads(json_data)
# Rebuild the credentials.
base = data.get("_base")
# Init base cred.
base_creds = None
if base.get('type') == 'ext... | Python | 1 |
"""Audio input/output components.
This package provides an abstraction layer for audio input and output operations,
allowing the Glados engine to work with different audio backends interchangeably.
Classes:
AudioIO: Abstract interface for audio input/output operations
SoundDeviceAudioIO: Implementation using ... | Python | 1 |
import time
import faiss
import numpy as np
def get_index(
train_data,
index_type,
max_nitem_train: int = None,
n_probe: int = 40,
use_gpu: bool = True,
):
"""
• Create FAISS index
• Train index using all the data
• Return index
Since we store L2 normalized fingerprints, L2, d... | Python | 1 |
offsets = word_cursor.select_word();
let start = self.offset_to_location(offsets.0);
let end = self.offset_to_location(offsets.1);
shape(start, end)
}
Transform::Line => {
let start_offset = self.byte_offset_of_line_index_snapped(s... | Rust | 0 |
al TRAINING_RESULTS
if TRAINING_RESULTS is None:
return {'status': 'error', 'message': 'no trained model available'}
asyncio.create_task(deploy_task(req))
return {'status': 'ok'}
async def test_deploy() :
model_id = 0
deployment_id = str(uuid.uuid4())
normalize_solution_file = 'normal... | Python | 1 |
fi::GtkSourceSpaceLocationFlags {
ffi::GtkSourceSpaceLocationFlags::from_bits_truncate(self.bits())
}
}
#[cfg(feature = "v3_24")]
#[doc(hidden)]
impl FromGlib<ffi::GtkSourceSpaceLocationFlags> for SpaceLocationFlags {
fn from_glib(value: ffi::GtkSourceSpaceLocationFlags) -> SpaceLocationFlags {
... | Rust | 0 |
d_dict = {
"ev0000003-Winning": "奥斯卡奖",
"ev0000223-Winning": "艾美奖",
"ev0000292-Winning": "金球奖",
"ev0000003-Nominated": "奥斯卡提名",
"ev0000223-Nominated": "艾美奖提名",
"ev0000292-Nominated": "金球奖提名",
"ev0000003-bestPicture-Winning": "最佳影片",
... | Python | 1 |
PathEffect",
"SkCornerPathEffect",
"SkDataTable",
"SkDiscretePathEffect",
"SkDrawable",
"SkLine2DPathEffect",
"SkPath2DPathEffect",
"SkPathRef_GenIDChangeListener",
"SkPicture",
"SkPixelRef",
"SkSurface",
// Types not needed (for now):
"SkDeque",
"SkDeque_Iter",
"... | Rust | 0 |
ates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# I... | Python | 1 |
)
if context:
context.research_focus = new_focus
context.context_metadata["focus_updated_at"] = datetime.utcnow().isoformat()
await self.save_research_context(
user_id=user_id,
project_id=project_id,
... | Python | 1 |
from collections import deque
def bfs_with_order_and_path(graph, start):
visited = set() # 방문한 노드를 저장하는 집합
parent = {node: None for node in graph}
queue = deque([start])
visited.add(start) # 시작 노드를 방문 처리
order = []
while queue:
node = queue.popleft()
order.append(node)
... | Python | 1 |
nitor_uri": asset_upload_status_monitor_uri,
},
).uri
headers: Dict[str, str] = {}
headers["Accept"] = 'application/vnd.adobe.dc+json; profile="https://dc-api.adobe.io/schemas/upload_status_v1.json"'
resp = self._client.request(
"GET",
url,
... | Python | 1 |
upllcount().bits(config.count) });
// Wait until pll is locked
// 0 = not locked, 1 = locked
while !self.pmc_sr.read().locku().bits() {}
}
/// Disable the UTMI PLL, disabling the USB bus and any clocks configured
/// to use it as a source.
pub fn disable_upll(&mut self) {
... | Rust | 0 |
et __end0 = __1.2.clone();
let __temp0 = __action18(
&__start0,
&__end0,
);
let __temp0 = (__start0, __temp0, __end0);
__action37(
__0,
__1,
__temp0,
)
}
fn __action45<
'input,
>(
__0: (ByteIndex, ::std::vec::Vec<Item>, ByteIndex),
) -> File
{
let... | Rust | 0 |
cent_layer[i * 2]
right_parent = most_recent_layer[i * 2 + 1]
count_node = CTNode.create_count_node(left_parent, right_parent)
layer.append(count_node)
# add connection to remaining nodes (when layer above is not a power of 2)
self.all_layers.appe... | Python | 1 |
cycle timer
pub callback: tls_timer_irq_callback, // < timeout callback function
pub arg: *mut c_void, // < parameter fot the timeout callback function
}
/** ENUMERATION definition of OS STATUS */
#[repr(C)]
#[derive(Clone, PartialEq, Debug)]
pub enum tls_os_status {
TLS_OS_SUCCESS = 0,
... | Rust | 0 |
[derive(Debug)]
pub struct Chunk {
pub nbytes: u32,
pub nrec: u32,
pub reads: Vec<ReadRecord>,
}
#[derive(Debug)]
pub struct CorrectedCBChunk {
remaining_records: u64,
corrected_bc: u64,
nrec: u32,
data: Cursor<Vec<u8>>, /*,
umis: Vec<u64>,
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.