text string | label_name string | labels int64 |
|---|---|---|
import spacy
from spacy.matcher import Matcher
nlp = spacy.load("fr_core_news_sm")
doc = nlp(
"Twitch Prime, le programme pour les membres d'Amazon destiné aux "
"fans de jeux vidéos, arrête l'une de ses fonctionnalités les plus "
"appréciées de cette offre tout-compris : l'absence de publicité. "
"La ... | Python | 1 |
# Diccionario de turistas inicial
turistas = {
"001": ["John Doe", "Estados Unidos", "12-01-2024"],
"002": ["Emily Smith", "Estados Unidos", "23-03-2024"],
"012": ["Julian Martinez", "Argentina", "19-09-2023"],
"014": ["Agustin Morales", "Argentina", "28-03-2024"],
"005": ["Carlos Garcia", "Mexico"... | Python | 1 |
sh.UniformFloatHyperparameter(
"learning_rate__LexicoGradientBoostingClassifier",
lower=0.01,
upper=0.5,
default_value=0.1,
)
n_estimators = csh.UniformIntegerHyperparameter(
"n_estimators__LexicoGradientBoostingClassifier",
**self.... | Python | 1 |
&mut self,
name: T,
inputs: &[&str],
sink: S,
) {
let inputs = inputs.iter().map(|&s| s.to_owned()).collect::<Vec<_>>();
let sink = SinkOuter {
buffer: Default::default(),
healthcheck: true,
inner: Box::new(sink),
inputs,
... | Rust | 0 |
::subnet_config::SchedulerConfig;
use thiserror::Error;
use ic_crypto::{
threshold_sig_public_key_to_der,
utils::ni_dkg::{self, initial_ni_dkg_transcript_record_from_transcript, InitialNiDkgConfig},
};
use ic_protobuf::registry::{
crypto::v1::PublicKey,
subnet::v1::{CatchUpPackageContents, SubnetFeatur... | Rust | 0 |
lename)
await ctx.send(file=file, embed=e, view=PlayerView(voice_client))
else:
await ctx.send(embed=e, view=PlayerView(voice_client))
if vol != -1:
voice_client.source.volume = vol / 100
else:
for track in play_list:
ctx.voice_client.add_track... | Python | 1 |
];
check_is_table(x, exp);
let x = process_w_table("grp-by {get first | >= 0} | map value --Table len", defs);
let exp = vec![
vec![o("key"), o("value")],
vec![Entry::from(Value::Bool(false)), n(1)],
vec![Entry::from(Value::Bool(true)), n(2)],
];
check_is_table(x, exp);
}
//... | Rust | 0 |
์ '{seg_col_x}'",
"fa": "استفاده از بخش مرتبط با مقدار '{seg_val_x}' از ستون '{seg_col_x}'.",
},
"report_no_evaluation_issues": {
"en": "No evaluation issues.",
"fr": "Aucun problème d'évaluation.",
"de": "Keine Bewertungsprobleme.",
"it": "Nessun problema di valutazione.... | Python | 1 |
.into()).into());
}: _(RawOrigin::Signed(caller.clone()), 0, 1u32.into())
verify {
let staking_info = crate::Pallet::<T>::staking_info(caller);
assert_eq!(staking_info, amount.into());
}
}
impl_benchmark_test_suite!(Pallet, crate::benchmarking::tests::new_test_ext(), crate::mock::Test);
use core::fmt;
/// POSI... | Rust | 0 |
, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x1f) | ((value as u16) & 0x1f);
self.w
}
}
impl R {
#[doc = "Bits 0:4 - 4:0\\]
Port 6 interrupt vector value"]
#[inline(always)]
pub fn p6iv(&self) -> P6IV_R {
P6IV_R::new((self.bits & 0x1f) as u8)
}
}
impl W {
#[... | Rust | 0 |
from enum import Enum
class StandardNamingConventions(Enum):
PASCAL_CASE = "pascalcase"
CAMEL_CASE = "camelcase"
UPPER_CASE = "uppercase" | Python | 1 |
v_atomic)]
impl_atomic!(AtomicI32);
#[cfg(rkyv_atomic_64)]
impl_atomic!(AtomicI64);
#[cfg(rkyv_atomic)]
impl_atomic!(AtomicU8);
#[cfg(rkyv_atomic)]
impl_atomic!(AtomicU16);
#[cfg(rkyv_atomic)]
impl_atomic!(AtomicU32);
#[cfg(rkyv_atomic_64)]
impl_atomic!(AtomicU64);
#[cfg(not(feature = "strict"))]
macro_rules! peel_tup... | Rust | 0 |
test]
#[ignore] // This test connects to an active deployment on Netlify (not ideal for CI!)
async fn e2e() {
dotenv::from_filename("./tests/.env.local").unwrap(); // For the Netlify deployment URL (excluded from Git)
let client = Client::new();
// We only run a single simple query test on the serverless sy... | Rust | 0 |
# SPDX-FileCopyrightText: Copyright (c) 2025 The Newton Developers
# SPDX-License-Identifier: Apache-2.0
#
# 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
#
# http://www.apache.org/licenses/LIC... | Python | 1 |
np.save(os.path.join(save_dir, f'{idx}.npy'), moments)
clip_img_feature = clip_img_model.encode_image(
clip_img_model_preprocess(Image.fromarray(clip_img)).unsqueeze(0).to(device))
clip_img_feature = clip_img_feature.detach().cpu().numpy()
np.save(os.path.join(save_... | Python | 1 |
, f)
# sort_index
f = lambda x: x.sort_index(inplace=True)
_check_f(data.copy(), f)
# fillna
f = lambda x: x.fillna(0, inplace=True)
_check_f(data.copy(), f)
# replace
f = lambda x: x.replace(1, 0, inplace=True)
_check_f(data.copy(), f)
... | Python | 1 |
nModeNV =
0;
pub const VkCoverageReductionModeNV_VK_COVERAGE_REDUCTION_MODE_TRUNCATE_NV:
VkCoverageReductionModeNV = 1;
pub const VkCoverageReductionModeNV_VK_COVERAGE_REDUCTION_MODE_MAX_ENUM_NV:
VkCoverageReductionModeNV = 2147483647;
pub type VkCoverageReductionModeNV = ::std::os::raw::c_uint;
pub type Vk... | Rust | 0 |
not be copied, modified, or distributed
// except according to those terms.
use boolean::CFBoolean;
use number::CFNumber;
use dictionary::CFDictionary;
use string::CFString;
fn main() {
/*let n = CFNumber::new_number(42 as i32);
io::println(fmt!("%d", (&n).retain_count() as int));
(&n).show();*/
let ... | Rust | 0 |
from llama_index.core.prompts import PromptTemplate
from llama_index.core.prompts.prompt_type import PromptType
EXTRACT_JSON_VALUE_FROM_SCHEMA_TEMPLATE = (
"""You are a mechanical enginner, specialized on creating, reading and understanding
data sheets. You are able to extract all relevant textual and position... | Python | 1 |
# Copyright 2023 Flower Labs GmbH. All Rights Reserved.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | Python | 1 |
s"))
media_type = d.pop("media_type")
name = d.pop("name")
publisher = d.pop("publisher")
total_episodes = d.pop("total_episodes")
type = cast(Literal["show"], d.pop("type"))
if type != "show":
raise ValueError(f"type must match const 'show', got '{type}'... | Python | 1 |
(&self, x: &BigInt, label: &str) -> G1 {
let x = BigNum::fromstring(x.to_str_radix(16));
let mut cipher: G1 = G1::new();
cipher.inf();
for i in 0..2 {
let ex_label = format!("{} {}", i.to_string(), label);
let mut h = hash_to_g1(&ex_label);
h = h.mul(... | Rust | 0 |
self, chunk: bytes) -> None:
if self._compress is not None:
if chunk:
chunk = self._compress.compress(chunk)
if not chunk:
return
if self._encoding == "base64":
buf = self._encoding_buffer
assert buf is not None
... | Python | 1 |
CryptVerifyDetachedMessageSignature(
pVerifyPara: PCRYPT_VERIFY_MESSAGE_PARA, dwSignerIndex: DWORD,
pbDetachedSignBlob: *const BYTE, cbDetachedSignBlob: DWORD, cToBeSigned: DWORD,
rgpbToBeSigned: *mut *const BYTE, rgcbToBeSigned: *mut DWORD,
ppSignerCert: *mut PCCERT_CONTEXT,
) -> B... | Rust | 0 |
import cv2
cam=cv2.VideoCapture(0)
fourrc=cv2.VideoWriter_fourcc(*'xVID')
out=cv2.VideoWriter("yenic.avi",fourrc,30.0,(640,480))
while cam.isOpened():
ret,frame=cam.read()
if not ret:
print("Görüntü yok")
break
out.write(frame)
cv2.imshow("Kamera",frame)
if cv2.waitKey(1) =... | Python | 1 |
2,
pub puintVal: *mut u32,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))]
impl ::core::marker::Copy for _wireVARIANT_0 {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))]
impl ::core::clone::Clone for _wireVARIANT_0 {
fn clone(&self) -> Self {
*self
... | Rust | 0 |
import os
from dotenv import load_dotenv
from datetime import timedelta
import cloudinary
# Load environment variables from a .env file
load_dotenv()
class Config:
SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI')
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY')
... | Python | 1 |
#/usr/bin/python
# coding=utf8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import time
import sys,os
from django.core.wsgi import get_wsgi_application
sys.path.extend(['smcsystem',])
os.environ.setdefault("DJANGO_SETTINGS_MOD... | Python | 1 |
^ buf[n] as u32) & 0xff) as usize] ^ (c >> 8);
n += 1;
}
c ^ 0xffffffff
}
const fn crc32(buf: &[u8]) -> u32 {
Self::update_crc32(0, buf)
}
}
impl Attribute<'_> for Fingerprint {
type Context = ();
const TYPE: u16 = 0x8028;
fn decode(_: Self::Context, msg... | Rust | 0 |
import simpleaudio as sa
wave_obj = sa.WaveObject.from_wave_file("resources/test1.wav")
play_obj = wave_obj.play()
play_obj.wait_done()
| Python | 1 |
unwrap();
self.lives_text = Text::new(_ctx, &new_lives, &self.font).unwrap();
}
// Function to check if the player lost or won
pub fn check_end_conditions(&mut self, _ctx: &mut Context) {
// Out of lives?
if self.lives == 0 {
self.game_over = true;
return;
... | Rust | 0 |
#!/usr/bin/env python3
from math import sumprod
from funcy import accumulate, constantly, count, interleave, lmap, lmapcat, map, repeat
from aoc_util import dbg, run_aoc
SP = type("Space", (), {"__int__": constantly(0), "__repr__": constantly(".")})()
def aoc09(data):
def checksum(disk):
return sumpro... | Python | 1 |
import threading
import time
def crawl(link, delay=3):
print(f"crawl started for {link}")
time.sleep(delay) # Blocking I/O (simulating a network request)
print(f"crawl ended for {link}")
links = [
"https://python.org",
"https://docs.python.org",
"https://peps.python.org",
]
# Start threads... | Python | 1 |
" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate regex;
extern crate tempdir;
extern crate time;
extern crate hyper;
extern crate url;
extern crate habitat_sup as su... | Rust | 0 |
.collect::<Vec<_>>()
.prop_map(move |vals| CsrMatrix {
rows,
cols,
vals,
indices: cidx_flattened.clone(),
offsets: ridx.clone(),
})
})
}
pub fn arb_matrix() -> im... | Rust | 0 |
id);
/// assert!(ret.is_ok());
/// println!("timer id: {:?}", timer_id);
///
/// let flags = 0;
/// let time = nc::itimerspec_t {
/// it_interval: nc::timespec_t::default(),
/// it_value: nc::timespec_t {
/// tv_sec: 1,
/// tv_nsec: 0,
/// },
/// };
//... | Rust | 0 |
raise ValueError("No active editor")
workbench.active_editor.api.do(action)
workbench.active_editor.cursor = workbench.active_editor.api.cursor.bit
workbench.active_editor.refresh()
else:
raise Invalid... | Python | 1 |
E_TOOL_TYPE_PENCIL", "4"),
("(gint) GDK_DEVICE_TOOL_TYPE_UNKNOWN", "0"),
("(gint) GDK_DEVICE_TYPE_FLOATING", "2"),
("(gint) GDK_DEVICE_TYPE_MASTER", "0"),
("(gint) GDK_DEVICE_TYPE_SLAVE", "1"),
("(gint) GDK_DIAMOND_CROSS", "36"),
("(gint) GDK_DOT", "38"),
("(gint) GDK_DOTBOX", "40"),
("(... | Rust | 0 |
ing::Greater,
(Location::End, Location::Line(_)) => Ordering::Greater,
(Location::None, Location::Line(_)) => Ordering::Less,
_ => Ordering::Equal,
});
(filename, log_items)
})
.collect()
}
fn main() {
let files = env::args()
... | Rust | 0 |
flags,
range_proof_flag,
range_proof_finish_flag,
copy_values_flag,
)
}
fn get_assertions(&self) -> Vec<Assertion<Self::BaseField>> {
// Assert the presence of the appropriate initial and final tree roots
let last_step = self.trace_length() - 1;
... | Rust | 0 |
import csv
import numpy
from PIL import Image
import os
size = 20
# Create gussian heatmap
def gaussian_kernel(variance):
x, y = numpy.mgrid[-size:size+1, -size:size+1]
g = numpy.exp(-(x**2+y**2)/float(2*variance))
return g
# Make the Gaussian by calling the function
variance = 10
gaussian_kernel_array... | Python | 1 |
scale::*;
use parseerr::*;
use utext::*;
use uversion::*;
use uiter::*;
use uenum::*;
use urep::*;
use udisplaycontext::*;
use uformattable::*;
use umisc::*;
use ufieldpositer::*;
use ucnv_err::*;
use ucasemap::*;
use udata::*;
pub type UBool = int8_t;
pub type UChar = ::libc::c_ushort;
pub type UChar32 = int32_t;
use... | Rust | 0 |
z16BitMonoPcm = 16,
/// Raw8Khz16BitMonoPcm stands for raw-8khz-16bit-mono-pcm
Raw8Khz16BitMonoPcm = 17,
/// Ogg16Khz16BitMonoOpus stands for ogg-16khz-16bit-mono-opus
Ogg16Khz16BitMonoOpus = 18,
/// Ogg24Khz16BitMonoOpus stands for ogg-24khz-16bit-mono-opus
Ogg24Khz16BitMonoOpus = 19,
/... | Rust | 0 |
# run training update
if self.step >= self.cfg.num_seed_steps:
self.agent.update(self.replay_buffer, self.logger, self.step)
next_obs, reward, done, _ = self.env.step(action)
# allow infinite bootstrap
done = float(done)
done_no_ma... | Python | 1 |
,
#[error("Client ID mismatch")]
ClientIdMismatch,
#[error(transparent)]
Jwt(#[from] jsonwebtoken::errors::Error),
#[error("serde_json error: {0}")]
SerdeJson(#[from] serde_json::Error),
#[error("hyper error: {0}")]
Hyper(#[from] hyper::Error),
#[error("http error: {0}")]
Http(#[from] hyper::http::Error),
}
... | Rust | 0 |
2017402331136)),
afk_timeout: 300,
embed_enabled: true,
embed_channel_id: Some(ChannelId::from(41771983444115456)),
verification_level: VerificationLevel::Low,
message_notifications: MessageNotificationLevel::AllMessages,
explicit_content_filter: E... | Rust | 0 |
"""
CS50P Final Project: Cache Decorator Performance Comparison
Tests SafeCache against native lru_cache with unhashable types
"""
from time import time as timetime, sleep
from functools import lru_cache
from safecache import SafeCache
# Test Configuration
ITERATIONS = 3
SLEEP_DURATION = 1 # Seconds per simulated wo... | Python | 1 |
d_mul(block_delta_as_u128)
.ok_or(Error::<T>::NumOverflow)?;
let total_tokens_supply = T::MultiCurrency::total_issuance(wrapped_asset_id);
let ratio = match total_tokens_supply.cmp(&Balance::zero()) {
Ordering::Greater => {
Rate::checked_from_rational(mnt_accrued, total_tokens_supply).ok_or(Error::<T>::... | Rust | 0 |
# These are not vendored from the crate - we exclude them to avoid busting caches
# when we change how we generate BUILD files and such.
"BUILD.bazel",
"WORKSPACE.bazel",
"WORKSPACE",
]),
tags = [
"cargo-raze",
"manual",
],
version = "1.1.2",
visib... | Rust | 0 |
2.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"
/>
</svg>
}
}
pub fn square_check_solid() -> Html {
return html!{
<svg
data-icon="square-check"
focusable=SVG_FOCUS
class=SVG_CLASS
role=SVG_ROLE
xmlns=SVG_XMLNS
... | Rust | 0 |
name: "Chieftain".to_string(), faction: "Tribal".to_string(), cost: 400, enabled: true}); }
unsafe { TABUNITS.add(TabUnit {id: 6, file_name: "7.png".to_string(), unit_name: "Mammoth".to_string(), faction: "Tribal".to_string(), cost: 2200, enabled: true}); }
unsafe { TABUNITS.add(TabUnit {id: 7, file_name: ... | Rust | 0 |
assert_equal(p, dict(nx.all_pairs_dijkstra_path(self.cycle)))
p = nx.shortest_path(self.grid, weight='weight')
validate_grid_path(4, 4, 1, 12, p[1][12])
def test_all_pairs_shortest_path_length(self):
l = dict(nx.shortest_path_length(self.cycle))
assert_equal(l[0], {0: 0, 1:... | Python | 1 |
for fkc in can_remove:
dependent_on = fkc.referred_table
if dependent_on is not table:
mutable_dependencies.discard((dependent_on, table))
candidate_sort = list(
topological.sort(
fixed_dependencies.union(mutable_depe... | Python | 1 |
#!/usr/bin/env python3
# Copyright © 2020-2025, Meheret Tesfaye Batu <meherett.batu@gmail.com>
# Distributed under the MIT software license, see the accompanying
# file COPYING or https://opensource.org/license/mit
from ..slip44 import CoinTypes
from ..eccs import SLIP10Secp256k1ECC
from ..consts import (
Info, E... | Python | 1 |
explaining_player = db.scalar(
select(Player).where(
Player.room_id == room.id, Player.role == PlayerRole.EXPLAINING
)
)
if explaining_player:
current_player = str(explaining_player.id)
# Формируем список игроков
players = []
for p in room.players:
user ... | Python | 1 |
_path.mkdir()
save_instance(model, self.data_path / user_id / "model_{}.pickle".format(user_id))
save_instance(strategy, self.data_path / user_id / "strategy_{}.pickle".format(user_id))
trade_account.save_account(self.data_path / user_id)
user_record = pd.read_csv(self.users_file, index_... | Python | 1 |
invalid pointer.
///
/// [`reaper_plugin_info_t`]: raw/struct.reaper_plugin_info_t.html
pub unsafe fn from_extension_plugin(
h_instance: raw::HINSTANCE,
rec: raw::reaper_plugin_info_t,
static_context: StaticExtensionPluginContext,
) -> Result<PluginContext, ContextFromExtensionP... | Rust | 0 |
concat!(
"Offset of field: ",
stringify!(vfio_iommu_spapr_tce_create),
"::",
stringify!(__resv1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<vfio_iommu_spapr_tce_create>())).window_size as *const _ as usize
},
16usi... | Rust | 0 |
"""Generate answers with local models.
Usage:
python3 data_format_conversion.py --csv-path ./data/ops_bench/运维领域评测数据集-v1.0.csv --jsonl-path ./data/ops_bench/question.jsonl
"""
import argparse
import json
import os
import pandas as pd
import shortuuid
def csv_to_jsonl(csv_path, jsonl_path):
df = pd.read_csv(csv... | Python | 1 |
import argparse
import torch
import matplotlib.pyplot as plt
from data import NoisyBSDSDataset
from argument import parse
from model import DnCNN, UDnCNN, DUDnCNN
import nntools as nt
from utils import DenoisingStatsManager, plot
def run(args):
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# datase... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING
from sanic import HTTPResponse
from src import secret
from .. import utils
from .base import WithGameLifecycle
from .team_state import Team
if TYPE_CHECKING:
from src.store import UserStore
from . import Game
class Users(WithGameLifecy... | Python | 1 |
reward = np.mean(all_rewards)
print(f"Ricompensa media su {num_episodes} episodi: {mean_reward:.2f}")
# ================= (6) Plot delle ricompense =================
plt.figure()
plt.plot(range(1, num_episodes+1), all_rewards, marker='o', label='Reward')
plt.axhline(mean_reward, color='r', linestyl... | Python | 1 |
# Copyright (C) 2014 Google Inc. All rights reserved.
#
# Redistribution and use 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 and the ... | Python | 1 |
_order_value'], nbinsx=20), row=2, col=1)
# Customer recency
if not customer_df.empty:
recency_counts = customer_df['recency_segment'].value_counts()
fig.add_trace(go.Bar(x=recency_counts.index, y=recency_counts.values), row=2, col=2)
# Product performan... | Python | 1 |
import random
# ─── QUESTION SELECTION ─────────────────────────────────────────────
def seleccionar_siguiente(vocab: list[dict],
weights: dict[str, float],
mode: str,
_label_image) -> tuple[str, str, list[str]]:
if mode == "Random":
... | Python | 1 |
(mapping, dimension=[20, 20, 20])
print(f"Reconstructed voxel grid with shape {voxel_grid.shape}")
# Sample colors
sampled_colors = {}
for voxel_key in mapping.keys():
coords = voxel_key[:3]
face_idx = voxel_key[3]
color = get_voxel_average_color(texture, coords, face_idx, m... | Python | 1 |
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
def fermat_last_theorem(limit):
x_values = []
y_values = []
z_values = []
valid_solution = False
for x in range(1, limit):
for y in range(x, limit):
z = np.cbrt(x**3 + y**3)
... | Python | 1 |
pub fn wglGetDefaultProcAddress();
// pub fn wglGetLayerPaletteEntries();
// pub fn wglGetPixelFormat();
pub fn wglGetProcAddress(lpszProc: LPCSTR) -> PROC;
pub fn wglMakeCurrent(hdc: HDC, hglrc: HGLRC) -> BOOL;
// pub fn wglRealizeLayerPalette();
// pub fn wglSetLayerPaletteEntries();
// p... | Rust | 0 |
})
def test_transform_destination_new_table(self):
# Add source and destination tables
self.init_state()
# Update transform while importing to destination table which is "New Table"
self.apply_user_action(['GenImporterView', 'Source', None, None, {}])
# Verify the new structure of source ... | Python | 1 |
())
} else {
None
}
});
let res: DatetimeChunked =
ChunkedArray::<Int64Type>::new_from_opt_iter(&name, it).into();
df_series.push(res.into_series())
... | Rust | 0 |
import sys
sys.stdin = open('input18382.txt')
def cal(operate, n1, n2):
n1 = int(n1)
n2 = int(n2)
if operate == '+':
return n2 + n1
elif operate == '-':
return n2 - n1
elif operate == '*':
return n2 * n1
else:
return n2 // n1
T = int(input())
for tc in range(1,... | Python | 1 |
from recbole.utils.logger import init_logger, set_color
from recbole.utils.utils import get_local_time, ensure_dir, get_model, get_trainer, \
early_stopping, calculate_valid_score, dict2str, init_seed, get_tensorboard, get_gpu_usage
from recbole.utils.enum_type import *
from recbole.utils.argument_list import *
__... | Python | 1 |
= np.transpose( np.squeeze(added_noise_data[0,:,:,:]), [1,2,0] )
cv2.imwrite("perturbation.png", added_noise + args.mean)
def main_batch(args):
"""Adversarial examples for semantic segmentation models evaluated over all images in a list file."""
if CheckAllDone(args):
print "Processing", args.im... | Python | 1 |
m.randint(images.shape[0])
target = torch.tensor(images[img_i], dtype=torch.float32)
pose = torch.tensor(poses[img_i], dtype=torch.float32)
rays_o, rays_d = get_rays(H, W, focal, pose)
optimizer.zero_grad()
rgb, depth, acc = render_rays(model, rays_o, rays_d, near=2., far=6., N_... | Python | 1 |
, Partial, PartialMapWithStr};
/// Parse result of `CData`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum ParseResult<T> {
/// Completely parsed.
Complete(T),
/// CDATA section closed unexpectedly.
CdataSectionClosed(Partial<T>),
/// Invalid Character.
Inva... | Rust | 0 |
e_base_api()
call_remove_knowledge_base_api()
if section == "Vector Search Endpoints":
with st.expander("Vector Search Endpoints"):
call_vector_search_submit_api()
call_query_api()
if section == "Dialog Endpoints":
with st.expander("Dialog Endpoints"):
... | Python | 1 |
import enum
from types import SimpleNamespace
from django.db.models import IntegerChoices
from django.utils.translation import gettext_lazy as _
def reverse_choices(choices):
output = {}
for choice in choices:
output[choice[0]] = choice[1]
return output
SYMPTOM_CHOICES = [
(1, "ASYMPTOMATIC... | Python | 1 |
import unittest
from SO_cwe327_0 import generate_fingerprint
from Crypto.Cipher import *
from Crypto.Cipher import DES
from Crypto.Cipher import AES
class TestCWE327_0(unittest.TestCase):
def test_correctness(self):
key = b'01234567'
iv = b'12345678'
fingerprint = generate_fingerprint(key, ... | Python | 1 |
}", transform);
world.create_entity()
.with(transform)
.with(platform.aabb.clone())
.with(Collider)
.with(mesh)
.with(material)
.build();
}
fn create_rocket(world: &mut World, rocket: &RocketConfig) {
debug!("Creating Rocket: {:?}", rocket);
let width = roc... | Rust | 0 |
1, l2, l3, l4, rho])
q = Matrix([q1, q2, q3])
u = Matrix([u1, u2, u3])
eval_m = lambdify((q, p), kane.mass_matrix)
eval_f = lambdify((q, u, p), kane.forcing)
eval_fhd = lambdify((q, u, p), fhd)
p_vals = [0.13, 0.24, 0.21, 0.34, 997]
q_vals = [2.1, 0.6655470375077588, 2.527408138024188] # S... | Python | 1 |
)
);
}
extern "C" {
#[doc = " @brief Initialize a mailbox."]
#[doc = ""]
#[doc = " This routine initializes a mailbox object, prior to its first use."]
#[doc = ""]
#[doc = " @param mbox Address of the mailbox."]
#[doc = ""]
#[doc = " @return N/A"]
#[doc = " @req K-MBOX-002"]... | Rust | 0 |
&self.state {
SessionState::WhoAreYouSent => false,
SessionState::RandomSent => false,
SessionState::AwaitingResponse(_) => false,
SessionState::Established(_) => true,
SessionState::EstablishedAwaitingResponse { .. } => true,
SessionState::Poison... | Rust | 0 |
[packrat_parser]
pub(crate) fn list_of_udp_port_identifiers(s: Span) -> IResult<Span, ListOfUdpPortIdentifiers> {
let (s, a) = list(symbol(","), port_identifier)(s)?;
Ok((s, ListOfUdpPortIdentifiers { nodes: (a,) }))
}
#[tracable_parser]
#[packrat_parser]
pub(crate) fn list_of_specparam_assignments(s: Span) ->... | Rust | 0 |
block_hash: header.hash(),
state: self.last_state,
};
Some(result)
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::collections::HashMap;
use chain::BlockHeader;
use db::{BlockHeaderProvider, BlockRef};
use network::Deployment;
use hash::H256;
use primitives::bytes... | Rust | 0 |
erable[Tensor]):
functorch model buffers (added se we don't break abstraction)
images (Tensor):
input images
labels (Tensor):
input labels
Returns:
Tensor:
model output for the given image-label pair :math:`z`
... | Python | 1 |
from freqtrade.util import decimals_per_coin, fmt_coin, round_value
from freqtrade.util.formatters import fmt_coin2
def test_decimals_per_coin():
assert decimals_per_coin("USDT") == 3
assert decimals_per_coin("EUR") == 3
assert decimals_per_coin("BTC") == 8
assert decimals_per_coin("ETH") == 5
def t... | Python | 1 |
puby,
message,
cfg,
trigger,
reset=False,
):
asymsca = OTAsymCrypto(target)
if reset:
target.reset_target()
# Clear the output from the reset
target.dump_all()
# Initialize our chip and catch its output
device_id, owner_page, boot_log, boot_measurements, version... | Python | 1 |
::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
pub fn set_staker_infos_and_mint(origin: OriginFor<T>,
infos: Vec<StakeInfo<T::AccountId,T::Balance>>) -> DispatchResult {
Self::mint_by_staker(Self::calc_reward_by_epoch())?;
Self::update_stakers(infos)
}
#[pallet::weight(10_000 + T::DbWei... | Rust | 0 |
def vyber_povolani():
print("=" * 40)
print("Zvol si své povolání:")
print("1 - Nájemný žoldák")
print("2 - Hacker")
print("3 - Plíživec")
print("=" * 40)
volba = input("Tvoje volba: ")
if volba == "1":
return "Nájemný žoldák"
elif volba == "2":
return "Hack... | Python | 1 |
_scores) if quality_scores else 0,
"min_quality_score": min(quality_scores) if quality_scores else 0,
"max_quality_score": max(quality_scores) if quality_scores else 0,
},
"recommendations": self.generate_recommendations(original_segments, final_segments, quality_... | Python | 1 |
e() {
println!("Encrypting a file will happen here.");
println!("Press enter to continue");
io::stdin().read_line(&mut String::new()).unwrap();
let mut file_to_encrypt = String::new();
let mut input = String::new();
let mut matrix_size: u32 = 0;
print!("Enter file name to be encrypted: ");
io::stdout()... | Rust | 0 |
stance': min_dist,
'cucumber_point': cucumber_points[cuc_pt],
'stem_point': stem_points[stem_pt],
'distance_type': 'mask'
}
else:
# Проверка по линии стебля
line_func, line_params = get_stem_center_li... | Python | 1 |
ndex - 1]
if prediction_loss_only:
return (loss, None, None)
logits = nested_detach(logits)
if len(logits) == 1:
logits = logits[0]
return (loss, logits, labels)
def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]):
"""
... | Python | 1 |
if let Some(backtrace) = e.backtrace() {
self.generic_message(kind, Some("debugging:"), format_args!("backtrace follows:"));
self.with_stream(kind, |s| {
writeln!(s, "{:?}", backtrace).expect("backtrace dump failed");
});
}
... | Rust | 0 |
# 트라이
# 계층 구조를 저장하는 방식
class Trie:
def __init__(self):
self.root = dict()
def insert(self, folders):
now = self.root
for folder in folders:
now = now.setdefault(folder,dict())
def dfs(self, now, level=0):
for nxt in sorted(now):
print(" "*level + nx... | Python | 1 |
import ctypes
import math
import time
import torch
def scatter_nd(indices, updates, shape):
"""pytorch edition of tensorflow scatter_nd.
this function don't contain except handle code. so use this carefully
when indice repeats, don't support repeat add which is supported
in tensorflow.
"""
ret... | Python | 1 |
import pygame
import sys
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Moving Ball")
WHITE = (255, 255, 255)
RED = (255, 0, 0)
ball_radius = 25
ball_x = screen_width // 2
ball_y = screen_height // 2
move_speed... | Python | 1 |
The signal was generated in userspace using a system call that allowed near arbitrary data to be passed, or inside the kernel using similar functionality.
///
/// The kernel has extremely weak checks validating the structure of such data matches its signal number and code.
///
/// The associated data is completely... | Rust | 0 |
ComArray::from_raw(outSize, out)) } else { err(hr) }
}}
#[inline] pub fn set_thumbprint(&self, value: &[u8]) -> Result<()> { unsafe {
let hr = ((*self.lpVtbl).put_Thumbprint)(self as *const _ as *mut _, value.len() as u32, value.as_ptr() as *mut _);
if hr == S_OK { Ok(()) } else { err(hr) }
... | Rust | 0 |
counter = 0
def get_id():
global counter
counter += 1
return str(counter)
| Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.