text string | label_name string | labels int64 |
|---|---|---|
{
let p = g.players.get(0).unwrap().borrow();
assert_eq!(p.cash(), 1440); // bought street
assert_eq!(s.asset.borrow().owner().unwrap(), p.turn_idx());
}
g.execute_turn(Dice::new(9, 0)); // Mongul moves to Electric Company
{
let p = g.players... | Rust | 0 |
_type(), shape)?;
Ok(tvec!(quantized_fact, scale_fact, zero_fact))
}
as_op!();
}
#[cfg(test)]
mod tests {
use super::*;
use tract_ndarray::arr1;
// Data for tests is from:
// https://github.com/onnx/onnx/blob/master/docs/Operators.md#DynamicQuantizeLinear
#[test]
fn test_scale... | Rust | 0 |
pub const KERB_REFRESH_POLICY_KDC: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Security_Authentication_Identity\"`*"]
pub const KERB_REFRESH_POLICY_KERBEROS: u32 = 1u32;
#[repr(C)]
#[doc = "*Required features: `\"Win32_Security_Authentication_Identity\"`*"]
pub struct KERB_REFRESH_POLICY_REQUEST {
pub Message... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class FailFaceUserInfo(object):
def __init__(self):
self._fail_code = None
self._fail_message = None
self._retry = None
self._unique_id = None
@property
def fai... | Python | 1 |
.mm(q_down, Q_proj_up_weight.T).reshape(B, C, nh, dq_nope + dq_rope)
q = q.transpose(1, 2)
q_rope = q[..., dq_nope:]
q[:, :, :, dq_nope:] = rope(q_rope, basis, prev_len)
kv_down = torch.mm(x.reshape(-1, d), KV_proj_down_weight.T).reshape(B, C, -1)
kv_cache[:, prev_len:total_len] = kv_down
kv_f... | Python | 1 |
iance in batch normalization.
batch_norm_scale: If True, uses an explicit `gamma` multiplier to scale the
activations in the batch normalization layer.
activation_fn: The activation function which is used in ResNet.
use_batch_norm: Whether or not to use batch normalization.
Returns:
An `arg_sco... | Python | 1 |
#!/usr/bin/env python
import sys
import socket
import struct
import telnetlib
import time
import re
import string
import base64
import random
#s = socket.create_connection(("127.0.0.1", 13337))
s = socket.create_connection(("54.164.173.236", 1337))
def interact():
t = telnetlib.Telnet()
t.sock = s
t.in... | Python | 1 |
buffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>>>,
pub testarrayofsortedstruct: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Ability>>>,
pub flex: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
pub test5: Option<flatbuffers::WIPOffset<flatbuffers::Vec... | Rust | 0 |
from maya.api import OpenMaya
from pymel.core import cmds, attributeQuery
from . import capi # &&& Need to move this to lib since it imports a neighbor
__all__ = [
'SHARED_SHAPE',
'isValidNurbsCurve',
'getNurbsShapes',
'uniformPointsOnCurve',
]
SHARED_SHAPE = 'sharedShapeData'
def isValidNurbsCur... | Python | 1 |
pass_reg);
LLVMInitializeTarget(pass_reg);
LLVMInitializeTransformUtils(pass_reg);
LLVMInitializeVectorization(pass_reg);
engine::add_llvm_symbols();
LLVMGetGlobalContext()
};
// Pass command line arguments to LLVM.
if let Some(args) = matches.values_of("llvm-args")... | Rust | 0 |
LAGS = 33554432u32;
#[doc = "*Required features: 'Win32_UI_Accessibility'*"]
pub const SKF_LWINLATCHED: STICKYKEYS_FLAGS = 1073741824u32;
#[doc = "*Required features: 'Win32_UI_Accessibility'*"]
pub const SKF_RWINLATCHED: STICKYKEYS_FLAGS = 2147483648u32;
#[doc = "*Required features: 'Win32_UI_Accessibility'*"]
pub con... | Rust | 0 |
vector_score = 0.0
if vector_weight > 0:
# Normalize paper embedding
paper_norm = np.linalg.norm(embedding)
if paper_norm > 0:
embedding = embedding / paper_norm
# Calculate cosine similarity
... | Python | 1 |
insert([miner.x, miner.y], cell);
// we add the whole cross as dangerous too, which is very “defensive” but whatever
for i in &[-1, 1] {
if let Some(cell) = game_state.cell(miner.x + i, miner.y).cloned() {
eprintln!("({}, {}) is dangerous", miner.x + i, miner.y);
... | Rust | 0 |
= status.start_date.as_ref() {
params.push(("start_date", format!("{start_date}")));
}
if let Some(finish_date) = status.finish_date.as_ref() {
params.push(("finish_date", format!("{finish_date}")));
}
ctx.data::<M... | Rust | 0 |
import boto3
import logging
from pydantic import EmailStr
from domain.entity.user import UserSignUp, UserSignIn, UserVerify, ChangePassword, ConfirmForgotPassword
from .config import env_vars
AWS_REGION_NAME = env_vars.AWS_REGION_NAME
AWS_COGNITO_APP_CLIENT_ID = env_vars.AWS_COGNITO_APP_CLIENT_ID
AWS_COGNITO_USER_POO... | Python | 1 |
resource_id.id))
})
.expect("Failed to find initialized resource")
}
fn write_resource(&mut self,resource_id:ResourceId,res:resources::ResourceParam< '_,>,) {
self.resources.insert(resource_id.into(), res.repr.to_owned());
}
/*fn get_resource(&mut self, res_id: ResourceId) -... | Rust | 0 |
d_file(&self.metrics_dir)?;
delete_app_file(&self.metrics_dir, &self.app_name)?;
}
MetricsStatus::OptedIn => {
let uuid = Uuid::new_v4();
self.uuid = Some(uuid);
write_uuid_file(&self.metrics_dir, &uuid.to_string())?;
... | Rust | 0 |
IC_M2_MIDIOUT: u32 = 33u32;
#[doc = "*Required features: `\"Win32_Media_Multimedia\"`*"]
pub const MM_CHROMATIC_M2_MIXER: u32 = 23u32;
#[doc = "*Required features: `\"Win32_Media_Multimedia\"`*"]
pub const MM_CHROMATIC_M2_MPEGWAVEIN: u32 = 35u32;
#[doc = "*Required features: `\"Win32_Media_Multimedia\"`*"]
pub const MM... | Rust | 0 |
currency: usize,
handler: JobHandler,
job_client: Client,
worker: String,
job_extensions: Extensions,
) {
let per_job_extensions = Rc::new(job_extensions);
ReceiverStream::new(job_queue)
.for_each_concurrent(concurrency, |job| {
let mut task = JobTask {
job,
... | Rust | 0 |
version.patch = 0;
}
Token::Minor => {
version.minor += amount;
version.patch = 0;
}
Token::Patch => version.patch += amount,
// set build metadata and prerelease
Tok... | Rust | 0 |
pub block_reward: BTreeMap<BlockNumber, U256>,
/// EXPIP-2 block height
pub expip2_transition: u64,
/// EXPIP-2 duration limit
pub expip2_duration_limit: u64,
/// Block reward contract transition block.
pub block_reward_contract_transition: u64,
/// Block reward contract.
pub block_reward_contract: Option<Bloc... | Rust | 0 |
_118_465_649,
-6_320_577_374_581_628_592,
7_208_698_530_190_629_697,
7_276_901_792_339_343_736,
-7_490_986_807_540_332_668,
4_133_292_154_170_828_382,
2_918_308_698_224_194_548,
-7_703_910_638_917_631_350,
-3_929_437_324_238_184_044,
-4_300_543_082_831_323_144,
-6_344_160_503_358... | Rust | 0 |
QueryTrail<Post, juniper_from_schema::Walked>,
//! ) -> FieldResult<Vec<Post>> {
//! // Check if the query includes the author
//! if let Some(_) = trail.author().walk() {
//! // Somehow preload the users to avoid N+1 query bugs
//! // Exactly how to do this depends on your s... | Rust | 0 |
to
/// create all plugin instances on request.
pub struct PluginsFactory {
list: Vec<Box<dyn PluginBuilder>>,
}
impl PluginsFactory {
/// Create a new empty plugin factory
pub fn new() -> PluginsFactory {
PluginsFactory { list: Vec::new() }
}
/// Add a new plugin builder to the factory
... | Rust | 0 |
def _fetch_instances(self):
pass
for i in range(len(self.threads)):
pass
self.threads[i]._fetch_instances()
@property
def streams(self):
if hasattr(self, '_m_streams'):
return self._m_streams
_pos = self._io.pos()... | Python | 1 |
error: format!("EdgeKV Error: {:?}", e),
})?;
}
Ok(())
}
fn find<'a>(
&'a self,
column: &'static str,
mode: BackendIteratorMode,
) -> Result<BackendIterator<'a>, Error> {
let db = self.db.get(column).ok_or(Error::EdgeKVError {
... | Rust | 0 |
import numpy as np
from collections import Counter
def BLEU(references, generated, max_grams=4, weights=None):
ref_list = [ref.lower().split(" ") for ref in references]
gen = generated.lower().split(" ")
cpn = np.empty((max_grams,), dtype=np.float32)
for n in range(1, max_grams+1):
gen_gram = ... | Python | 1 |
def goodDay():
print("Good Day")
goodDay()
| Python | 1 |
}
}
use crate::frame;
use crate::frame::Frame;
use std::io::Stdout;
use std::io::Write;
use std::io;
use crossterm::QueueableCommand;
use crossterm::style::{SetBackgroundColor, Color};
use crossterm::terminal::{Clear, ClearType};
use crossterm::cursor::MoveTo;
pub fn render(stdout: &mut Stdout, cur_frame: &Frame, ... | Rust | 0 |
erokee","pl":"Cherokee","mi":"Catalan","ms":"Cherokee","sv":"Cherokee","uk":"Черокі","pt":"Cherokee","vi":"Cherokee","hu":"Cherokee","cy":"Cherokee","gu":"શેરોકી","eo":"Cherokee","km":"ឈែ","no":"Cherokee","bg":"Чероки","es":"Cherokee","cv":"Чероксем","et":"Cherokee","ja":"チェロキー族","da":"Cherokee","bn":"চেরোকী","it":"Che... | Python | 1 |
son.dumps(terpenes_measurement, indent=4, sort_keys=True))
# Test importing residual solvents by Agilent GC
residual_solvents_measurement = test_import_agilent_gc_residual_solvents()
print('\nResidual Solvent Measurement: ✓\n')
if verbose:
print(json.dumps(residual_solvents_measurement, ind... | Python | 1 |
self.plot(initial_frame)
def plot(self, idx=0):
"""Show the video preview."""
if self.video is None:
return
# Get image data
frame = self.video[idx]
# Re-size the preview image
height, width = frame.shape[:2]
img_length = max(height,... | Python | 1 |
", ts);
assert!(cert.expired(ts) == true);
let ts = NaiveDateTime::parse_from_str("2028-11-13 23:56:04", "%Y-%m-%d %H:%M:%S").unwrap();
assert!(cert.expired(ts) == true);
}
#[test]
pub fn test_nebula_certificate_verify_private_key() {
let mut pub_key = String::new();
... | Rust | 0 |
None
}
}).next()
.unwrap();
let selection: Selection = selection_set.into();
assert_eq!(
selection,
Selection(vec![SelectionItem::Field(SelectionField {
alias: None,
name: "animal".to_s... | Rust | 0 |
v8_buy_condition_1_enable'])}/v8_2={int(row['v8_buy_condition_2_enable'])}/v8_3={int(row['v8_buy_condition_3_enable'])}/v8_4={int(row['v8_buy_condition_4_enable'])}"
logger.info(f"{metadata['pair']} - candle: {row['date']} - buy condition - details: {buy_cond_details}")
return dataframe
... | Python | 1 |
assert_array_almost_equal(transformer.y_means, expected_y_means)
# std should be nearly 1
assert abs(np.std(trans_train_dset.y) - 1) < 1e-4
# validation set has a different distribution
trans_valid_dset = model_pipeline.model_wrapper.transform_dataset(valid_dset, fold=i)
# val... | Python | 1 |
import random
import time
from confluent_kafka import Consumer, OFFSET_BEGINNING
from src.configs.logger import get_logger
from src.configs.kafka import BROKER_URL
class SpotifyConsumer:
MIN_DELAY = 1
MAX_DELAY = 5
def __init__(self, topics, group_id, messages_handler, offset_earliest=False,
... | Python | 1 |
" => OS::Linux,
"macos" => OS::MacOS,
"netbsd" => OS::NetBSD,
"none" => OS::None,
"openbsd" => OS::OpenBSD,
"psp" => OS::Psp,
"redox" => OS::Redox,
"solaris" => OS::Solaris,
"solid_asp3" => OS::SolidAsp3,
"tvos" ... | Rust | 0 |
L_A::PSEL_0
}
#[doc = "Checks if the value of the field is `PSEL_1`"]
#[inline(always)]
pub fn is_psel_1(&self) -> bool {
*self == PSEL_A::PSEL_1
}
#[doc = "Checks if the value of the field is `PSEL_2`"]
#[inline(always)]
pub fn is_psel_2(&self) -> bool {
*self == PSEL_A:... | Rust | 0 |
55, 0xffffffff);
let mut x1683: u32 = 0;
let mut x1684: fiat_p384_u1 = 0;
fiat_p384_subborrowx_u32(&mut x1683, &mut x1684, x1682, x1657, 0xffffffff);
let mut x1685: u32 = 0;
let mut x1686: fiat_p384_u1 = 0;
fiat_p384_subborrowx_u32(&mut x1685, &mut x1686, x1684, x1659, 0xffffffff);
let mut x1687: u32 = 0;... | Rust | 0 |
pub fn SDL_AtomicTryLock(lock: *mut SDL_SpinLock) -> SDL_bool;
}
extern "C" {
/// \brief Lock a spin lock by setting it to a non-zero value.
///
/// \param lock Points to the lock.
pub fn SDL_AtomicLock(lock: *mut SDL_SpinLock);
}
extern "C" {
/// \brief Unlock a spin lock by setting it to 0. Always... | Rust | 0 |
}
}
pub struct Butterfly7<T> {
twiddle1: Complex<T>,
twiddle2: Complex<T>,
twiddle3: Complex<T>,
direction: FftDirection,
}
boilerplate_fft_butterfly!(Butterfly7, 7, |this: &Butterfly7<_>| this.direction);
impl<T: FftNum> Butterfly7<T> {
pub fn new(direction: FftDirection) -> Self {
Sel... | Rust | 0 |
opy_weight = cross_entropy_weight
self.dice_weight = dice_weight
self.mask_weight = mask_weight
self.use_auxiliary_loss = use_auxiliary_loss
self.no_object_weight = no_object_weight
self.output_auxiliary_logits = output_auxiliary_logits
self.num_attention_heads = self.de... | Python | 1 |
# -*- coding: utf-8 -*-
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
labels = ["Jun", "Jul", "Aug", "Sep"]
sizes = [20, 30, 40, 10]
# 圓餅圖顏色
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
# 長條圖 位置
plt.subplot(1, 2, 1)
xticks = range(0, len(labels))
# 長條圖以labels... | Python | 1 |
def main():
months ={
"January": "01", "February": "02", "March": "03", "April": "04",
"May": "05", "June": "06", "July": "07", "August": "08",
"September": "09", "October": "10", "November": "11", "December": "12"
}
while True:
try:
date =input("Date: ").strip()... | Python | 1 |
}
pub fn keyval_to_unicode(keyval: u32) -> u32 {
assert_initialized_main_thread!();
unsafe { gdk_sys::gdk_keyval_to_unicode(keyval) }
}
pub fn keyval_to_upper(keyval: u32) -> u32 {
assert_initialized_main_thread!();
unsafe { gdk_sys::gdk_keyval_to_upper(keyval) }
}
pub fn pixbuf_get_from_surface(
... | Rust | 0 |
Opts;
use anyhow::{anyhow, Context};
use clap::Clap;
use phrase::PhraseOpts;
use private::PrivateOpts;
use public::PublicOpts;
use seed::SeedOpts;
use std::io::Read;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::str::FromStr;
use std::{env, io};
use tracing::Level;
use tracing_subscriber::EnvFilter;
mod a... | Rust | 0 |
dst_chars_ptr_size: u32,
convert_type: u32,
convert_target: u32,
) -> u32 {
dst_chars_ptr.write_bytes(0, dst_chars_ptr_size as usize);
return UCSStr::convert_raw(
src_chars_ptr,
dst_chars_ptr,
src_chars_ptr_size as usize,
int_to_convert_type(convert_type),
... | Rust | 0 |
.base32_len();
assert!(len < 1024, "Every tagged field data can be at most 1023 bytes long.");
writer.write_u5(u5::try_from_u8(tag).expect("invalid tag, not in 0..32"))?;
writer.write(&try_stretch(
encode_int_be_base32(len as u64),
2
).expect("Can't be longer than 2, see assert above."))?;
paylo... | Rust | 0 |
request.chat_template if chat_request.chat_template else None,
)
result_dict, runtime_graph = await self.megaservice.schedule(
initial_inputs={"input": prompt}, llm_parameters=parameters
)
for node, response in result_dict.items():
# Here it suppose the last micro... | Python | 1 |
import regress
import sys
import unittest
from unicorn import *
from unicorn.mips_const import *
CODE = (
b'\xf8\xff\x01\x24' # addiu $at, $zero, -8
b'\x24\xe8\xa1\x03' # and $sp, $sp, $at
b'\x09\xf8\x20\x03' # jalr $t9
b'\xe8\xff\xbd\x23' # addi $sp, $sp, -0x18
b'\xb8\xff\xbd\x27' # addiu $sp... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
# Define the categories
categories = ['0-RETRIEVE', '1-COMPARE', '2-CALC-CHANGE',
'3-CALC-COMPLEX', '4-CALC-AND-JUDGE', '5-EXPLAIN-FACTORS', '6-OTHER-ADVANCED']
# Create angles for the plot
N = len(categories)
angles = [n / float(N) * 2 * np.pi for n ... | Python | 1 |
import dotenv
dotenv.load_dotenv()
import re
import os
from firecrawl import FirecrawlApp, ScrapeOptions
def web_search_tool(query: str):
"""
Web Search Tool.
Args:
query: str
The query to search the web for.
Returns
A list of search results with the website content in Mar... | Python | 1 |
k(&PacketNumberRange::new(packet_number, packet_number));
let expected_blocked_sync_period = 3 * rtt_estimator
.pto_period(1, PacketNumberSpace::ApplicationData)
- rtt_estimator.smoothed_rtt();
assert_eq!(
Some(write_context.current_time + expected_blocked_sync_period),
manager... | Rust | 0 |
(Deserialize, Debug)]
pub struct Team {
#[serde(rename = "_id")]
pub id: i64,
pub background: Option<String>,
pub banner: String,
pub created_at: DateTime<UTC>,
pub display_name: String,
pub info: String,
pub logo: String,
pub name: String,
pub updated_at: DateTime<UTC>,
pub ... | Rust | 0 |
st in monitorServer.items():
key = str(_n)
try:
ms = int(st.get('latency') or 0)
except Exception:
ms = 0
items.append((key, max(0, ms)))
# 稳定顺序:按 key 排序
items... | Python | 1 |
import unittest
import numpy as np
from scipy.stats import multivariate_normal
from pyapprox.analysis.parameter_sweeps import (
get_hypercube_parameter_sweeps_samples,
get_gaussian_parameter_sweeps_samples
)
class TestParameterSweeps(unittest.TestCase):
def test_get_hypercube_parameter_sweeps_samples(sel... | Python | 1 |
pass # applySysPathWorkaround is False
for p in reversed(l_vars['PYTHON_EXTENSIONS_PATHS']):
sys.path.insert(1 if not applySysPathWorkaround else 0, p)
if os.name == 'nt':
if sys.version_info[:2] >= (3, 8): # https://github.com/python/cpython/pull/12302
for p in l_va... | Python | 1 |
import sys
import socket
from tqdm import tqdm
from netaddr import IPAddress
from scapy.all import sr1, ARP # pylint: disable=no-name-in-module
from concurrent.futures import ThreadPoolExecutor
from .host import Host
from evillimiter.console.io import IO
class HostScanner(object):
def __init__(self, inte... | Python | 1 |
share_private_mappings: bool,
/// Singlestep instructions and dump register states when replaying towards <trace-event> or
/// later
#[structopt(short = "t", long = "trace")]
trace_event: Option<FrameTime>,
/// Allow replay to run on any CPU. Default is to run on the CPU stor... | Rust | 0 |
Fr> {
let n = self.0.len();
let mut out = vec![E::Fr::zero(); n];
for i in 0..n {
out[i] = self.0[i]
+ &(x * &(self.1[i]
+ &(x * &(self.2[i]
+ &(x * &(self.3[i] + &(x * &(self.4[i] + &(x * &(self.5[i]))))))))));
}
... | Rust | 0 |
Acquire the lock.
// Loops (spins) until the lock is acquired.
// Holding a lock for a long time may cause
// other CPUs to waste time spinning to acquire it.
pub unsafe extern "C" fn acquire(lk: *mut Spinlock) {
pushcli(); // disable interrupts to avoid deadlock.
if holding(lk) {
cpanic("acquire");
... | Rust | 0 |
AA22");
hi_mux.add_signal_type(0, SignalType::LowVoltageCMOS_3v3);
Self {
sig_in: hi_in,
sig_out: hi_out,
sig_inout: hi_inout,
sig_aa: hi_aa,
sig_mux: hi_mux,
}
}
pub fn xem_7010() -> OpalKellyHostInterface {
let mut hi... | Rust | 0 |
.bits(word) });
}
}
pub trait GpioRegisters<RegisterAccess>
where
RegisterAccess: BankGpioRegisterAccess,
{
fn write_out_en_clear(&self, word: u32) {
RegisterAccess::write_out_en_clear(word);
}
fn write_out_en_set(&self, word: u32) {
RegisterAccess::write_out_en_set(word);
}
... | Rust | 0 |
evice color, 3 colorants
Device3 = 50,
// Device color, 4 colorants
Device4 = 51,
// Device color, 5 colorants
Device5 = 52,
// Device color, 6 colorants
Device6 = 53,
// Device color, 7 colorants
Device7 = 54,
// Device color, 8 colorants
... | Rust | 0 |
p
# └── interface_beta
# └── beta.hpp
# Map: filename => [title, link_name]
d_map = {
"interface_alpha": [
"Directory interface_alpha",
"dir_include_interface_alpha"
],
"one_two_three": [
"Directory o... | Python | 1 |
!(shadow, Ok(Value::Bool(false)));
test_file!(expr, Ok(Value::Bool(true)));
test_file!(undefined_var, Err);
test_file!(type_error, Err);
test_file!(rec_error, Err);
test_file!(rec_func, Ok(Value::Bool(true)));
test_file!(rec_shadow, Ok(Func));
test_file!(func_shadow, Ok(Value::Bool(true)));
test_file!(rec_chain, Ok(Fun... | Rust | 0 |
: use from/into? But these require consuming the command, so we need some better memory model to avoid deallocation
impl<T> Cmd<T>
where
T: FuseIn + core::fmt::Debug,
{
pub fn to_u8buf(&self) -> Vec<&[u8]> {
let rawcmd = unsafe {
::core::slice::from_raw_parts(
(&self.header as *const fuse_in_header) as *cons... | Rust | 0 |
um_peaks, prominence=peaks_prominence)
if not recent_peaks or not recent_troughs:
st.error("❌ 未能检测到足够的峰值或谷值。请调整峰值数量或显著性。")
st.stop()
# For simplicity, take the highest peak and the lowest trough
swing_high = recent_peaks[0]
swing_low = recent_troughs[0]
high_price = df['high'].ilo... | Python | 1 |
#! /usr/bin/env python3
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet
from sklearn.linear_model import SGDRegressor, Lars, LassoLars
from sklearn.linear_model import RidgeCV, LassoCV, ElasticNetCV
import pyEDM as EDM
#------------------------------------------------------------
#-------... | Python | 1 |
1],
[1, 2],
[2, 3],
[3, 4],
[0, 5],
[5, 6],
[6, 7],
[7, 8],
[0, 9],
[9, 10],
[10, 11],
[11, 12],
[0, 13],
[13, 14],
[14, 15],
[15, 16],
[0, 17],
[17, 18],
[18, 19],
[1... | Python | 1 |
import argparse
import pathlib
import cv2
""" Gathers all the images of a folder and its subfolders and saves them in a new folder.
Only supports jpeg images for now.
Args:
input (str): path to the starting folder
output (str): path to the output folder
"""
if __name__ == "__main__":
parser = ar... | Python | 1 |
class Solution:
def reverseBits(self, n: int) -> int:
binary_str = bin(n)[2:].zfill(32) # Convert to binary and pad to 32 bits
reversed_str = binary_str[::-1] # Reverse the string
return int(reversed_str, 2) # Convert back to integer
| Python | 1 |
or = super::validator::portugal::PortugalValidator;
assert_eq!(validator.extract_citizen("11084129 8 ZX8").is_none(), true);
}
}//! This module provides the diff functionality for [`TreeSync`].
//!
//! # About
//!
//! This module provides the [`TreeSyncDiff`] struct, that allows mutable
//! operations on ot... | Rust | 0 |
amount,
skey,
rewind_nonce,
private_nonce,
extra_data,
Some(message),
))
}
/// Verify a proof
pub fn verify(
secp: &Secp256k1,
commit: Commitment,
proof: RangeProof,
extra_data: Option<Vec<u8>>,
) -> Result<(), secp::Error> {
let result = secp.verify_bullet_proof(commit, proof, extra_data);
result.map... | Rust | 0 |
import os
from unittest import TestCase
from camel.models import ModelFactory
from camel.types import ModelPlatformType, ModelType
from dotenv import load_dotenv
from camel_database_agent.database.manager import DatabaseManager
from camel_database_agent.database.schema import (
DatabaseSchemaParse,
SchemaPars... | Python | 1 |
_exec, sqlite3_last_insert_rowid, SQLITE_OK};
use crate::SqliteError;
/// Managed handle to the raw SQLite3 database handle.
/// The database handle will be closed when this is dropped and no `ConnectionHandleRef`s exist.
#[derive(Debug)]
pub struct ConnectionHandle(NonNull<sqlite3>);
/// A wrapper around `Connectio... | Rust | 0 |
{
IResult::Done(rem, rd) => (rem, rd),
IResult::Incomplete(ii) => { return IResult::Incomplete(ii); }
IResult::Error(e) => { return IResult::Error(e); }
};
offset += rem.len() - rem2.len();
debug!("n {:?}: offset {}", n, offset);
// spec says pad to 4 bytes, but traffic shows t... | Rust | 0 |
feats = feats.mean(-1)
assert feats.dim() == 1, feats.dim()
feats = feats.view(1, -1)
padding_mask = torch.BoolTensor(feats.shape).fill_(False)
inputs = {
"source": feats.half().to(device),
"padding_mask": padding_mask.to(device),
"output_layer": 9, # layer 9
}
... | Python | 1 |
hidden_size, input_size]
r_shape = [3 * hidden_size, hidden_size]
b_shape = [4 * hidden_size]
parameter_x = ov.parameter(x_shape, name="X", dtype=np.float32)
parameter_h_t = ov.parameter(h_t_shape, name="H_t", dtype=np.float32)
parameter_w = ov.parameter(w_shape, name="W", dtype=np.float32)
par... | Python | 1 |
tx.send((x, y, color)).expect("Failed to send pixel!");
});
}
}
// Update and display progress bar - uncomment for small perf. inc.
let work_units = if denoise {
2 * WINDOW_WIDTH * WINDOW_HEIGHT
} else {
WINDOW_WIDTH... | Rust | 0 |
et_laps_by_name(self, surname: str):
"""Получение пароля LAPS по имени сотрудника"""
matches = self.employee_manager.search(surname)
if not matches:
self.log_message(f"Сотрудник '{surname}' не найден")
return
if len(matches) > 1:
self.show... | Python | 1 |
;
let values = sheet_values.values;
if values.is_empty() {
bail!(
"unable to retrieve any data values from Google sheet for reviewer leaderboard {}",
sheet_id
);
}
// Iterate over the rows.
for (row_index, row) in values.iter().enumerate() {
if row_i... | Rust | 0 |
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
class BudgetAnalytic(models.Model):
_inherit = 'budget.analytic'
@api.model_create_multi
def create(self, vals_list):
budgets = super().create(vals_list)
if len(budgets) == 1 and self.... | Python | 1 |
import matplotlib.pyplot as plt
import numpy
from tensorflow.keras.preprocessing.sequence import pad_sequences
# Function to plot model metrics
def plot_metrics(history):
# Plot training & validation accuracy values
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'],... | Python | 1 |
db_bed_file.to_csv("db_bed.temp.bed",sep="\t",index=None,header=None)
gvcf_df = self.gvcf_df(self._gvcf)
gvcf_df_bed_file = gvcf_df[['chr','start','end']]
gvcf_df_bed_file.to_csv("gvcf_bed.temp.bed",sep="\t",index=None,header=None)
a = pybedtools.BedTool("db_bed.temp.bed")
... | Python | 1 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'c:\Users\wii03\Desktop\video_downloader\download_tab\video_subwindow\video.ui'
#
# Created by: PyQt5 UI code generator 5.15.10
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file ... | Python | 1 |
#!/usr/bin/env python
# -*- Coding: utf-8 -*-
"""
Modulos : Descargar de RUC
Sub-Modulos: RUC
Empresa : Vision Banco S.A.E.C.A
Autor : Derlis Caballero
Fecha : 30/01/2020
Nombre : setrest01
Objetivo : Se encarga de realizar scraping en la pagina de la SET para
descargar zip de ruc por controlm
... | Python | 1 |
(
bounce_threshold_velocity=0.2,
),
)
# robot
robot_cfg: ArticulationCfg = SHADOW_HAND_CFG.replace(prim_path="/World/envs/env_.*/Robot").replace(
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.5),
rot=(1.0, 0.0, 0.0, 0.0),
joint_... | Python | 1 |
# Copyright (c) 2025, NVIDIA CORPORATION.
import datetime
import numpy as np
import pandas as pd
from cudf import DataFrame
from cudf.testing import assert_eq
def test_issue_165():
df_pandas = pd.DataFrame()
start_date = datetime.datetime.strptime("2000-10-21", "%Y-%m-%d")
data = [(start_date + datetime... | Python | 1 |
= f64x2::new(0., 8.);
let b: f64x2 = f64x2::new(2., 9.);
let e: f64x2 = f64x2::new(8., 9.);
let r: f64x2 = transmute(vuzp2q_f64(transmute(a), transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vabal_high_u8() {
let a: u16x8 = u16x8::new... | Rust | 0 |
self.receive(rbuf)?;
}
[] => (),
}
idx += 1;
}
Ok(())
}
}
<gh_stars>0
mod lex;
mod parsing;
mod machine;
mod cell;
#[derive(Debug)]
pub enum Error {
Unimplemented(String),
InvalidType(String),
Parsing(String),
Stac... | Rust | 0 |
.user32.GetForegroundWindow()
ctypes.windll.user32.SetForegroundWindow(hwnd)
return ctypes.windll.user32.MessageBoxW(hwnd, message, title, style)
else:
raise Exception("Unsupported OS")
def resource_path(relative):
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, ... | Python | 1 |
import torch
from einops import rearrange
def init_kwargs(kwargs_dict):
d = {}
if kwargs_dict is not None:
d = kwargs_dict
return d
def get_pos_encoding(pos, dim, dtype = torch.double):
'''
pos: positions to encode
dim: the embedding dimension (should match the transformer i... | Python | 1 |
import pytest
from livekit.agents import vad
from livekit.plugins import silero
from . import utils
SAMPLE_RATES = [16000, 44100] # test multiple input sample rates
VAD = silero.VAD.load(
min_speech_duration=0.5,
min_silence_duration=0.75,
)
@pytest.mark.parametrize("sample_rate", SAMPLE_RATES)
async de... | Python | 1 |
::new(cli.input_reader().expect("cannot open file"));
let Input { player_data } = Input::from_buffer(input_reader).expect("cannot parse input");
// Part 1: Deterministic game
let part1_answer = {
let game_config = GameConfig::new(10, 1000, 3);
let game_result =
simulate_determin... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# в саду сорвали цветы
garden = ('ромашка', 'роза', 'одуванчик', 'ромашка', 'гладиолус', 'подсолнух', 'роза', )
# на лугу сорвали цветы
meadow = ('клевер', 'одуванчик', 'ромашка', 'клевер', 'мак', 'одуванчик', 'ромашка', )
# создайте множество цветов, произрастающих в с... | Python | 1 |
ct'>({pct_text})</span>" if pct_text else ""
col.markdown(f"""
<div class="kpi-card">
<div class="kpi-title">{title} {pct_html}</div>
<div class="kpi-value">{value}</div>
</div>
""", unsafe_allow_html=True)
# === Cálculos ===
total_ven... | Python | 1 |
let fresh0 = p;
p = p.offset(1);
info!("{}", char::from(*fresh0 as u8));
}
if p == start.offset(50) {
info!("...");
}
info!("<--\n");
}
pub fn dump_slice(buf: &[u8]) {
info!("\nCurrent input buffer is -->");
if buf.len() > 50 {
info!("{}...", buf[..50].display()... | Rust | 0 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from peda.utils import *
def enable_log(peda, filename):
peda.execute('set logging off') # prevent nested call
peda.execute('set height 0') # disable paging
peda.execute('set logging file %s' % ... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.