text string | label_name string | labels int64 |
|---|---|---|
import pandas as pd
import matplotlib.pyplot as plt
# load data of various cryptos from kaggle datasets:
# https://www.kaggle.com/sudalairajkumar/cryptocurrencypricehistory/downloads/cryptocurrencypricehistory.zip
# if you run in jupyter, simply make sure that all CSV files are in the same folder as the (.ipynb) note... | Python | 1 |
struct CacheConfig {
pub cache_type: CacheType,
pub memory_cache_config: InMemorySizeBoundedLruCacheConfig,
pub disk_cache_config: DiskCacheConfig,
}
/// Factory method for cache
pub fn get_cache<K, V>(config: &CacheConfig) -> Option<Box<dyn Cache<K, V> + Send + Sync>>
where
K: 'static + Hash + Eq + C... | Rust | 0 |
d_cars = [car for car in cars if car.arrived]
arrived_cars.sort(key=lambda x: x.commute_time)
num_arrived_cars = len(arrived_cars)
early_arrival_bonus = sum(car.score - F for car in arrived_cars)
# Calculate statistics
arrival_percentage = (num_arrived_cars / V) * 100 if V > 0 else 0
... | Python | 1 |
import requests
import utils.utils as utils
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
def validate(pluginargs, args):
#
# Plugin Args
#
# --url https://domain.com -> gives the URL to the application
# --domain DOMAIN ->... | Python | 1 |
import yaml
from src import conv_onet
def load_config(path, default_path=None):
"""
Loads config file.
Args:
path (str): path to config file.
default_path (str, optional): whether to use default path. Defaults to None.
Returns:
cfg (dict): config dict.
"""
# load con... | Python | 1 |
rgs()
# 1) Build a config (could also parse from arguments).
# In real usage, you'd parse your CLI arguments or environment variables.
config = Config(
retrieval_method = args.retriever_name, # or "dense"
index_path=args.index_path,
corpus_path=args.corpus_path,
retr... | Python | 1 |
pub fn txucastgb(&self) -> TXUCASTGB_R {
TXUCASTGB_R::new((self.bits & 0xffff_ffff) as u32)
}
}
<gh_stars>0
// WARNING: this file is auto-generated by xtask gen and may be overwritten
use super::*;
/// Unexpected HTTP status code.
pub const E_STATUS_UNEXPECTED : HResultError = HResultError::from_con... | Rust | 0 |
{
let mode = hw.display.get_mode().to_bios();
let page = hw.display.cur_page();
let cols = hw.display.get_mode().cols() as u8;
bios_print!("Get video mode: page={}, mode={}, cols={}", page, mode, cols);
cpu.set_reg(BReg::AH, cols);
cpu.set_reg(BReg::AL, mode); // Video mode
c... | Rust | 0 |
a']
eta = self.heuristics[current, city] ** params['beta']
probabilities.append(tau * eta)
probabilities = np.array(probabilities)
probabilities /= probabilities.sum()
next_city = np.random.choice(unvisited, p=proba... | Python | 1 |
) => (None, Some(e), Some(chunks)),
};
return Ok(Self::MadeFullRequest {
airnode,
request_id,
requester_request_count,
chain_id,
requester,
endpoint_id,
sponsor,
sponso... | Rust | 0 |
f32)| x.0 as u64),
"pagerank",
vec![RootTimestamp::new(0)],
move |input1, input2, output, notificator| {
// receive incoming edges (should only be iter 0)
input1.for_each(|_iter, data| {
... | Rust | 0 |
import math
import os
import random
import re
import sys
#
# Complete the 'beautifulTriplets' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER d
# 2. INTEGER_ARRAY arr
#
def beautifulTriplets(d, arr):
# Write your code here
res=0
... | Python | 1 |
;
__KONST__
}};
}
use hyper::{
body::{aggregate, Body},
client::HttpConnector,
header::{HeaderValue, CONTENT_TYPE, USER_AGENT},
Method, Request, StatusCode, Uri,
};
use hyper_rustls::HttpsConnector;
use std::time::{Duration, Instant};
use crate::{credentials, Credentials};
// === error ==... | Rust | 0 |
: info.channel.primary,
cbw: format!("{:?}", info.channel.cbw.to_fidl().0),
secondary80: info.channel.cbw.to_fidl().1,
},
disconnect_source: info.disconnect_source.inspect_string(),
time_since_channel_switch?: info.time_since_channel_switch.map(|d| d.into_nanos()),
... | Rust | 0 |
fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 14)) | ((value as u32 & 0x03) << 14);
self.w
}
}
#[doc = "Field `DMA_APBPERI_SHA_PMS_CONSTRAIN_SRAM_WORLD_1_PMS_2` reader - dma_apbperi_sha_pms_constrain_sram_world_1_pms_2"]
pub struct DMA_APBPERI_SHA_PMS_CONSTRAIN_SRAM... | Rust | 0 |
tate_action.json" -exec rm -rf {} \;'.replace("<dir>", dic_path["PATH_TO_WORK_DIRECTORY"])
os.system(cmd_delete_model)
os.system(cmd_delete_work)
results_table.append([np.average(all_rewards), np.average(all_queue_len), np.average(all_travel_time)])
results_table.append([np.std(all_rewards), np... | Python | 1 |
n.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.
It differs from a similar function in cv2.cvtColor: `BGR <-> YCrCb`.
In OpenCV, it implements a JPEG conversion. See more details in
https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.
Args:
img (ndarray): The input image. It accepts:
... | Python | 1 |
import requests
from jsonpath import jsonpath
HOST = 'https://cloud.seafile.com'
sess = requests.Session()
class TestSeafileInterface:
"""
2.查看所有资料库(library中的list libraries)
curl -H 'Authorization: Token {{token}}' {{host}}/api2/repos/
URL: {{host}}/api2/repos/
请求方法:get
header: Authorization:Token {{token}}
jso... | Python | 1 |
` variant
///
/// Error Code `42230`
#[display(fmt = "Notes mustn't be empty!")]
NoteEmpty,
/// `428 PRECONDITION REQUIRED`
///
/// Error Code `42800`
#[display(fmt = "This request is required to be conditional; try using \"If-Match\"")]
PreconditionRequired,
/// `429 TOO MANY ... | Rust | 0 |
syntax tree traversal.
//!
//! Each method of [`QueryVisitor`] is a hook that can be overridden to customize the behavior when
//! visiting the corresponding type of node. By default, the methods don't do anything. The actual
//! walking of the ast is done by the `walk_*` functions. So to run a visitor over the whole
... | Rust | 0 |
tokio::process::Command;
/// use command_group::AsyncCommandGroup;
///
/// let mut child = Command::new("/bin/cat")
/// .arg("file.txt")
/// .group_spawn()
/// .expect("failed to execute child");
///
/// let ecode = child.wait()
/// ... | Rust | 0 |
],
'nesting_comment': [
(r'\(;', Comment.Multiline, '#push'),
(r';\)', Comment.Multiline, '#pop'),
(r'[^;(]+', Comment.Multiline),
(r'[;(]', Comment.Multiline),
],
'string': [
(r'\\[\dA-Fa-f][\dA-Fa-f]', String.Escape), # must ... | Python | 1 |
t('merchantName', 'N/A')}"
if order.get('vanId'):
result += f"\nVAN ID: {order.get('vanId')}"
if order.get('rrn'):
result += f"\nRRN: {order.get('rrn')}"
if order.get('vanIfscCode'):
result += f"\nVAN IFSC Code: ... | Python | 1 |
fn default() -> Self {
unsafe { std::mem::MaybeUninit::zeroed().assume_init() }
}
}
/// The opcode for `DRI2::WaitSBC` requests.
///
/// If this value appears in [`xcb_protocol_request_t::opcode`], and
/// [`xcb_protocol_request_t::ext`] is [`XcbDri2::xcb_dri2_id()`], then the type of the request is
//... | Rust | 0 |
st_pos(d: u32) -> bool {
(d & 0xffc00000) == 0x7d000000
}
pub const fn is_LDR_H_ldst_pos(d: u32) -> bool {
(d & 0xffc00000) == 0x7d400000
}
pub const fn is_STR_32_ldst_pos(d: u32) -> bool {
(d & 0xffc00000) == 0xb9000000
}
pub const fn is_LDR_32_ldst_pos(d: u32) -> bool {
(d & 0xffc00000) == 0xb94000... | Rust | 0 |
#
"""
Exercício
Peça ao usuário para digitar seu nome
Peça ao usuário para digitar a sua idade
Se nome e idade forem digitados:
Exiba
Seu nome é {nome}
Seu nome invertido é {nome invertido}
Seu nome contém (ou não) espaços
Seu nome tem {n} letras
A primeira letra do seu nome é {letra}
A ulti... | Python | 1 |
::BrTrue(lbl) | B::BrFalse(lbl) => {
*lbl = map[lbl].clone();
}
_ => (),
}
}
}
}
<gh_stars>1-10
#[cfg(target_arch = "x86")]
fn main() { }
#[cfg(target_arch = "x86_64")]
fn main() { }
<gh_stars>1-10
// Copyright 2014-2016 The Rust Project Devel... | Rust | 0 |
::StructOpt;
#[derive(Debug, Clone, StructOpt)]
pub struct Config {
#[structopt(short, long, default_value = "0.0.0.0")]
pub host: String,
#[structopt(short, long, default_value = "5000")]
pub port: u16,
}
impl Config {
pub fn from_args() -> Self {
StructOpt::from_args()
}
}
use super:... | Rust | 0 |
class TestExpectsClassmethod:
def setUpClass(self):
pass
@pytest.mark.parametrize("args", [
(), # without type/mapping
("test_doc", {"_meta": {}}), # with type/mapping
])
@es_test
def test_temporary_index(args):
index = "test_index"
with temporary_index(index, *args):
... | Python | 1 |
gn_corners = False
else:
self.align_corners = None
if 'learned-3x3' in mode:
# mimic a bilinear interpolation by nearest neigbor upscaling and
# a following 3x3 conv. Only works as supposed when the
# feature maps are upscaled by a factor 2.
... | Python | 1 |
less_than_or_equal(self, other: Self) -> bool {
self.less_than_or_equal_bm(other).declassify() != 0
}
// Comparison functions returning a bit mask (0x0..0 or 0xF..F).
#[cfg_attr(feature = "use_attributes", in_hacspec)]
fn not_equal_bm(self, other: Self) ... | Rust | 0 |
from locust import task, run_single_user
from locust import FastHttpUser
class login(FastHttpUser):
host = "http://localhost:5000"
default_headers = {
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.5",
"Connection": "keep-alive",
"DNT": "1",
... | Python | 1 |
ab(lineArr[1], lineArr[2])
if retDict['ResultSet']['Error'] == 0:
lat = float(retDict['ResultSet']['Results'][0]['latitude'])
lng = float(retDict['ResultSet']['Results'][0]['longitude'])
print "%s\t%f\t%f" % (lineArr[0], lat, lng)
fw.write('%s\t%f\t%f\n' % (line, ... | Python | 1 |
OTE: the weight initialization in `linear_init` would cause NaN when training with custom datasets.
# linear_init(self.enc_score_head)
constant_(self.enc_score_head.bias, bias_cls)
constant_(self.enc_bbox_head.layers[-1].weight, 0.0)
constant_(self.enc_bbox_head.layers[-1].bias, 0.0)
... | Python | 1 |
= np.asarray([[msg.twist.twist.angular.x], [msg.twist.twist.angular.y], [msg.twist.twist.angular.z]])
v_b = np.asarray([[msg.twist.twist.linear.x], [msg.twist.twist.linear.y], [msg.twist.twist.linear.z]])
xyz = np.asarray([[msg.pose.pose.position.x], [msg.pose.pose.position.
y], [msg.pose.pose.... | Python | 1 |
0x1001ea9: {'char': 'ẩ', 'xkey_name': 'acircumflexhook'},
0x1001eaa: {'char': 'Ẫ', 'xkey_name': 'Acircumflextilde'},
0x1001eab: {'char': 'ẫ', 'xkey_name': 'acircumflextilde'},
0x1001eac: {'char': 'Ậ', 'xkey_name': 'Acircumflexbelowdot'},
0x1001ead: {'char': 'ậ', 'xkey_name': 'acircumflexbelowdot'},... | Python | 1 |
ind") {
RunLevel::Bind
} else if name.ends_with("::render") {
RunLevel::Render
} else if name.ends_with("::release") {
RunLevel::Release
} else if name.ends_with("::resize") {
RunLevel::Resize
} else {
RunLevel::Standard
... | Rust | 0 |
ost '''
if host in self.inventory['_meta']['hostvars']:
return self.inventory['_meta']['hostvars'][host]
elif self.args.host and self.inventory['_meta']['hostvars']:
match = None
for k, v in self.inventory['_meta']['hostvars'].items():
if self.invento... | Python | 1 |
ine(tf: *mut sfTransform, other: *const sfTransform);
pub fn sfTransform_translate(tf: *mut sfTransform, x: f32, y: f32);
pub fn sfTransform_rotate(tf: *mut sfTransform, angle: f32);
pub fn sfTransform_rotateWithCenter(tf: *mut sfTransform, angle: f32, cx: f32, cy: f32);
pub fn sfTransform_scale(tf: *mu... | Rust | 0 |
mehow clean
model = self.models[i]
training = np.concatenate([folds[x] for x in fold_indices if x!=i],
axis=0)
validation = folds[i]
print(training, validation)
out_dir = create_directories(evaluation_path, "group_" + str(... | Python | 1 |
from __future__ import annotations
import asyncio
from inspect import signature
from typing import Any, Callable, Coroutine, TypeVar, Union
Input = TypeVar("Input")
# Output type should implement __concat__, as eg str, list, dict do
Output = TypeVar("Output")
async def gated_coro(semaphore: asyncio.Semaphore, coro:... | Python | 1 |
''' Q1. stock price, one transaction
Given an array A, maximize: A[i]-A[j], where i>j
Q2. stock price, multiple transaction (one transaction a time)
Given an array A. maximize: sigma A[s[j]] - A[b[j]] where 0<=b[j] < s[j]<=len(A)-1 and b[j+1] > s[j]
b[i] stands for the index of ith buying, s[i] ith... | Python | 1 |
# wafer_level_packaging.py
import numpy as np
class WaferPackage:
def __init__(self, num_layers=5, interlayer_temp_limit=80):
self.num_layers = num_layers
self.interlayer_temp_limit = interlayer_temp_limit
self.layer_temps = np.zeros(num_layers)
self.heat_generation_rate = np.rando... | Python | 1 |
(), name="counter").start()
console()
def players():
global White_Playing, board
Time_Stamp = main.Time_Stamp
player = main.player
if main.player[pointer] != 'Human' and game_ongoing:
#Perform ai actions
print("------------------ CALLED AI -----------------------------")
new_t... | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright (c) 2023-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | Python | 1 |
import os
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtCore import Qt, QSize
# المسار الأساسي للمشروع للوصول إلى الملفات مثل الأيقونات.
# بنفترض هنا إن utils.py موجود في src
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def create_default_icons():
"""
بيضمن وجود الأيقونات الافت... | Python | 1 |
have no relations between features and target."""
data = get_synthetic_input_data(N_SAMPLES, N_FEATURES, random_state=1)
data = get_random_target_data(data)
train_data, test_data = train_test_data_setup(data)
pipeline = generate_pipeline()
pipeline.fit(input_data=train_data)
roc_auc_value_trai... | Python | 1 |
# -*- coding: utf-8 -*-
__title__ = 'transliterate.contrib.languages.hy.data.default'
__author__ = 'Artur Barseghyan'
__copyright__ = '2013-2018 Artur Barseghyan'
__license__ = 'GPL-2.0-only OR LGPL-2.1-or-later'
__all__ = (
'mapping',
'reversed_specific_mapping',
'reversed_specific_pre_processor_mapping',... | Python | 1 |
import socket
import sys
import os
from colorama import Fore, Style, init
# Initialize colorama
init(autoreset=True)
def clear_screen():
os.system("clear")
def banner():
print(Fore.CYAN + Style.BRIGHT + r"""
_ \ __| ... | Python | 1 |
import os
import cv2
import numpy as np
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
# Rutas de acceso
ruta_destapado = "C:\\Users\\Edward\\Downloads\\Destapado"
ruta_oculto = "C:\\U... | Python | 1 |
"""
@PRIMARY: cfg-035
@PRIMARY_DESC: If no CPT to NI mapping is configured via the DLC API, LNet shall associate the NI with all existing CPTs.
@SECONDARY: cfg-040, cfg-045, cfg-055, cfg-060, cfg-065
@DESIGN: N/A
@TESTCASE:
- initialize the system
- add tcp
- add peers on tcp using the API
- validate peers are multi-ra... | Python | 1 |
use std::collections::HashMap;
#[derive(Clone, Debug)]
pub struct QualifiedName {
nsuri: Option<String>,
prefix: Option<String>,
localname: String,
}
// TODO: we may need methods that return a string slice, rather than a copy of the string
impl QualifiedName {
pub fn new(nsuri: Option<String>, prefix: Option... | Rust | 0 |
-deflate";
#[repr(u8)]
#[derive(Debug, Clone)]
pub enum WindowBit {
Eight = 8,
Night,
Ten,
Eleven,
Twelve,
Thirteen,
Fourteen,
FifTeen,
}
impl Default for WindowBit {
fn default() -> Self {
Self::Eight
}
}
#[derive(Debug, Clone, Default)]
pub struct DeflateConfig {
... | Rust | 0 |
field: ",
stringify!(sg_limits),
"::",
stringify!(max_image_array_layers)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<sg_limits>())).max_vertex_attrs as *const _ as usize },
20usize,
concat!(
"Offset of field: ",
s... | Rust | 0 |
::*;
# use std::time::SystemTime;
# // Create a simple schema for streaming text posts
# let schema_doc = Document::new(fogpack!({
# "req": {
# "name": { "type": "Str" },
# },
# "entries": {
# "post": {
# "type": "Obj",
# "req": {
# "text": { "type": "... | Rust | 0 |
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# This work is licensed under a Creative Commons
# Attribution-NonCommercial-ShareAlike 4.0 International License.
# You should have received a copy of the license along with this
# work. If not, see http://creativecommons.org/licenses/by-nc-... | Python | 1 |
r1.clone()),
Err(AddrError::Unsupported("Given PartialNodeAddr type can't be converted into RemoteNodeAddr"))
);
assert_eq!(
RemoteNodeAddr::try_from(locator_with_port.clone()),
Err(AddrError::Unsupported("Given PartialNodeAddr type can't be converted into RemoteNodeA... | Rust | 0 |
ces as needed. The string is
never truncated. If specified the fillchar is used instead of spaces.
"""
return s.rjust(width, *args)
# Center a string
def center(s, width, *args):
"""center(s, width[, fillchar]) -> string
Return a center version of s, in a field of the specified
width. padde... | Python | 1 |
',
'requirements': []
}
# Quick installer
methods['quick'] = {
'available': True,
'priority': 4,
'description': 'Quick installation with defaults',
'description_zh': '使用默认设置快速安装',
'function': self.quick_install,
... | Python | 1 |
subcommand(subcommand: Option<(&str, &ArgMatches)>) -> Result<Self, Error>;
/// Assign values from `ArgMatches` to `self`.
fn update_from_subcommand(
&mut self,
subcommand: Option<(&str, &ArgMatches)>,
) -> Result<(), Error>;
/// Append to [`App`] so it can instantiate `Self`.
///
... | Rust | 0 |
t: RVA, minimum_length: usize) -> Result<String> {
const END_OF_ASCII: u8 = 0x7F;
const SPACE: u8 = 0x20;
const TAB: u8 = 0x9;
const NEWLINE: u8 = 0xA;
const LINEFEED: u8 = 0xD;
let buf: Vec<u8> = (offset..std::u64::MAX)
.map(|offset| self.map.get(offset))
... | Rust | 0 |
from itertools import permutations
graph = 'EB EA AB AF BH FC HC HD GD GC'.split()
matrix = '248 157 456 136 23 34 28 17'.split()
print(*range(1, 9))
for i in permutations('ABCDEFGH'):
if all(str(i.index(x) + 1) in matrix[i.index(y)] for x, y in graph):
print(*i)
| Python | 1 |
turn pd_data
with session_context(test_session):
with reactive.isolate():
df._value.set(render.DataGrid(pd_data))
with pytest.raises(ValueError) as e:
await df.update_cell_value("a", row=0, col="b")
assert "Column 'b'" in str(e.value)
with p... | Python | 1 |
let coord_1 = imageproc::point::Point {
x: pixels.0.x as i32,
y: pixels.0.y as i32,
};
let coord_2 = imageproc::point::Point {
x: pixels.1.x as i32,
y: pixels.1.y as i32,
};
let coord_3 = imageproc::point::... | Rust | 0 |
ample_width: u8,
sample_height: u8,
sample: Vec<bool>,
cache: WeightsCache,
rng: &'a dyn Fn() -> f32
}
fn process_weights(sample: &Vec<bool>, sample_width: u8, sample_height: u8, n: u8) -> Vec<f32> {
let mut weights: Vec<f32> = vec![0.0; 1 << (n * n)];
let nsize = usize::from(n);
let pat... | Rust | 0 |
e last n_intervals - c rows
are then set to 0.
"""
n_intervals, n_coeffs = features[0].shape
n_lags = self.n_lags
self._set("n_intervals", n_intervals)
self._set("n_coeffs", n_coeffs)
# TODO: implement checker as outside function
# if n_lags > 0 and n_... | Python | 1 |
b: Vec<u8>,
id_s: Vec<u8>,
msg1: Vec<u8>,
password_scalar: G::Scalar,
}
impl<G: Group> Spake2<G> {
/// Start with identity `idA`.
///
/// Uses the system RNG.
#[cfg(feature = "getrandom")]
#[cfg_attr(docsrs, doc(cfg(feature = "getrandom")))]
pub fn start_a(password: &Password, id_a:... | Rust | 0 |
upload
def handle_file_upload(_event: param.parameterized.Event | None = None) -> None:
"""Handles file upload and updates the text input with the file content."""
if file_input.value:
try:
yaml_content = file_input.value.decode("utf-8")
yaml_input.value = yaml_content
ex... | Python | 1 |
self.sess.opts.trace_scoreboard {
debugln!("[SB][VHDL] arch for {:?} is {:?}", id, node);
}
if self.sb.arch_table.borrow_mut().insert(id, node).is_some() {
panic!("node should not exist");
}
Ok(node)
}
pub fn lldecl<I>(&self, id: I) -> Result<ll... | Rust | 0 |
] as a percentage of the radius.
((outer_df.sqrt() - inner_df.sqrt()) / radius as f64)
.min(1.0)
.max(-1.0)
})
.collect()
}
/// Compresses a Vec<f64> into a Vec<u8> for efficiency.
///
/// The highest `cutoff` percent of values in the range (0-255) will be us... | Rust | 0 |
cfg( feature = "bindgen" ) ] mod bindgen ;
#[ cfg( feature = "juliex" ) ] mod juliex ;
#[ cfg( feature = "threadpool" ) ] mod threadpool ;
#[ cfg( feature = "async_std" ) ] use async_std :: AsyncStd ;
#[ cfg( feature = "bindgen" ) ] use bindgen :: Bindgen ;
#[ cfg( feature = "j... | Rust | 0 |
for VComp {
fn transform(from: &'a str) -> Option<String> {
Some(from.to_owned())
}
}
impl<'a> Transformer<Option<&'a str>, Option<String>> for VComp {
fn transform(from: Option<&'a str>) -> Option<String> {
from.map(|s| s.to_owned())
}
}
impl PartialEq for VComp {
fn eq(&self, ot... | Rust | 0 |
_eq!()` analogue that prints the error with line number information instead of
/// panicking.
#[macro_export]
macro_rules! nih_debug_assert_eq {
($left:expr, $right:expr $(,)?) => (
if cfg!(debug_assertions) && $left != $right {
$crate::util::permit_alloc(|| $crate::log::debug!(concat!("Debug as... | Rust | 0 |
.62 us] std. dev. [5.6028 us 15.213 us]
median [138.33 us 143.23 us] med. abs. dev. [1.7507 ms 8.4109 ms]";
let parsed = parse_criterion_out(with_throughput);
assert_eq!(
parsed,
vec![CriterionResult {
name: "merkletree/blake2s/128".into(),
s... | Rust | 0 |
b'\r'
) {
if code[j] == b'\\' || code[j] == b'/' || code[j] == b'|' || code[j] == b'=' ||
code[j] == b'#' || code[j] == b'*'
{ panic!("Valid name not found: {}.", std::str::from_utf8(code).unwrap()) };
j += 1;
}
let mut i : usize = j;
while i < code.len() &&... | Rust | 0 |
?} to {}",
edn, "HashSet"
)))
})
})
.collect::<Result<HashSet<T>, Error>>(),
_ => Err(build_deserialize_error(
&edn,
std::any::type_name::<HashSet<T>>(),
)),
... | Rust | 0 |
_declare_options: self.config.queues.clone(),
prefetch_count: Mutex::new(self.config.prefetch_count),
};
broker
.set_prefetch_count(self.config.prefetch_count)
.await?;
Ok(broker)
}
}
/// An AMQP broker.
pub struct AMQPBroker {
uri: AMQPUri,
/// ... | Rust | 0 |
ckToken::JumpBackward => {
let idx = brackets.pop().unwrap_or_else(|| { panic!("Mismatched brackets: {}", loc); });
collapsed[idx] = match collapsed.get(idx).unwrap_or_else(|| {
panic!("No tokens found at specified stack location: {}", idx);
})
... | Rust | 0 |
# Copyright 2024 Huawei Technologies Co., Ltd
#
# 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 law or agreed to... | Python | 1 |
from deeplite_torch_zoo.src.object_detection.yolo.heads.detect import Detect
from deeplite_torch_zoo.src.object_detection.yolo.heads.v8.detect_v8 import DetectV8
from deeplite_torch_zoo.src.object_detection.yolo.heads.yolox.detectx import DetectX | Python | 1 |
bserver")
})
.expect("Failed to add udbserver hook");
Ok(())
} else {
udbserver_entry(uc, port, code_hook, mem_hook)
}
}
fn udbserver_entry(uc: &mut Unicorn<()>, port: u16, code_hook: Hook, mem_hook: Hook) -> DynResult<()> {
if GDBSTUB.is_some() {
return Ok(());
... | Rust | 0 |
, *optional*, defaults to `True`):
Whether or not to return a [`~schedulers.scheduling_ddpm.DDPMSchedulerOutput`] or `tuple`.
Returns:
prev_sample (TODO): updated sample in the diffusion chain. derivative (TODO): TODO
"""
pred_original_sample = sample_prev + sigma_p... | Python | 1 |
label_inputs[0][t]] for t in range(0, len(label_inputs[0]))]
output_probs[i] = torch.mean(torch.stack(token_probs, dim=-1)).item()
return output_probs
@torch.inference_mode()
def hidden(self, args):
# args:
# prompt: str - prompt to extract hidden states from
# ... | Python | 1 |
with pytest.raises(FileTypeException, match="Could not identify file type of given bytes because input is not valid Base-64"):
detect_file_type_from_base64(invalid_b64_bytes)
def test_detect_file_type_from_base64_data_url_no_comma(self, mocker: MockerFixture):
# Test data URL without comma (sho... | Python | 1 |
}
}
<reponame>tianchengli/flatdata
// Do not edit: This code was generated by flatdata's generator.
pub mod a {
pub mod schema {
pub mod structs {}}
#[derive(Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Bar {
Value = 0,
}
impl flatdata::helper::Int for Bar {
const IS_SIGNED: bool = false;
}
}
pub mod b {
pu... | Rust | 0 |
bind" => _ev in &data.on_change => {
change => {
obj.update_text_items();
obj.repaint();
}
}
};
let mut label = LabelWidgetBuilder {
rect: Default::default(),
graph: graph.into(),
dat... | Rust | 0 |
# Notes
///
/// Some methods that set options on `Socket` require two system calls to set
/// there options without overwriting previously set options. We do this by
/// first getting the current settings, applying the desired changes and than
/// updating the settings. This means that the operation is **not** atomic.... | Rust | 0 |
3D11_QUERY = 4i32;
#[doc = "*Required features: `\"Win32_Graphics_Direct3D11\"`*"]
pub const D3D11_QUERY_OCCLUSION_PREDICATE: D3D11_QUERY = 5i32;
#[doc = "*Required features: `\"Win32_Graphics_Direct3D11\"`*"]
pub const D3D11_QUERY_SO_STATISTICS: D3D11_QUERY = 6i32;
#[doc = "*Required features: `\"Win32_Graphics_Direct... | Rust | 0 |
(ROUTE)
}
/// Display the user info main data
fn display_human_result(user_info: Self::Item) {
println!("{}\n", "User Information");
print_info("id", user_info.id.as_str());
print_info("username", user_info.username.as_str());
print_info("email", user_info.email.as_str());
... | Rust | 0 |
istogram_historic_layers(infos: LayerMapInfo, minimum_sizes: list[int | float]) -> Histogram:
def log_layer(layer: HistoricLayerInfo) -> HistoricLayerInfo:
log.info(
f"{layer.layer_file_name} {human_bytes(layer.layer_file_size)} ({layer.layer_file_size} bytes)"
)
return layer
... | Python | 1 |
rZ / (NearZ - FarZ);
let Height: f32 = CosFov / SinFov;
// Note: This is recorded on the stack
let rMem: XMVECTORF32 = XMVECTORF32 { f: [
Height / AspectRatio,
Height,
fRange,
fRange * NearZ
]};
// Copy from memory to SSE register
... | Rust | 0 |
= crate::configure::load_rest_config(&document_path)?;
if !rest_config.switch {
return Ok(());
}
// 全局共享状态数据
let share_state = Arc::new(ShareState {
config: (
crate::configure::load_config(&document_path).unwrap(),
rest_config.clone(),
),
client... | Rust | 0 |
();
assert!(out_file.exists());
if let Some(path) = env::var_os("PATH") {
let mut paths = env::split_paths(&path).collect::<Vec<_>>();
let current_dir = env::current_dir().expect("could not determine current dir");
paths.insert(0, current_dir.join("target/debug"));
... | Rust | 0 |
. If this file exists,
# clear the entire directory and download with this script instead
if os.path.exists(stamp) and not glob.glob(
os.path.join(sysroot, ".*_is_first_class_gcs")):
with open(stamp) as s:
if s.read() == url:
return
print("Installing Debian %s... | Python | 1 |
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m = len(obstacleGrid)
n = len(obstacleGrid[0])
# dp[i][j] := unique paths from (0, 0) to (i - 1, j - 1)
dp = [[0] * (n + 1) for _ in range(m + 1)]
dp[0][1] = 1 # Can also set dp[1][0] = 1
for i in range... | Python | 1 |
}
#[test]
fn clean_keywords_before_search() {
let mut index = Index::new(0.01);
index.ingest("file1.txt".to_string(), "word1 word2\nword3").expect("Unable to ingest data");
assert_eq!(vec!["file1.txt"], index.search("(word1) Word2, word3?").unwrap().unwrap());
}
#[test]
fn... | Rust | 0 |
import cv2
from picamera2 import Picamera2,Preview
cam = Picamera2()
camera_config = cam.create_preview_configuration(main={'format': 'RGB888','size':(3840,2160)})
cam.configure(camera_config)
cam.start()
while True:
try:
image = cam.capture_array()
# Process the image using OpenCV
c... | Python | 1 |
width: usize,
height: usize,
) -> Result<(), ErrorCode> {
if self.status.get() == Status::Idle {
self.setup_command.set(false);
let buffer_len = self.buffer.map_or_else(
|| panic!("st77xx: buffer is not available"),
|buffer| buffer.len() - 1,
... | Rust | 0 |
import uuid
class __UserState:
username: str
selected_lobby: int
id: uuid.UUID
def __init__(self):
self.username = ''
self.selected_lobby = 0
self.lobby_players = []
self.id = uuid.uuid4()
def __str__(self):
return f"username={self.username}, selected_... | Python | 1 |
_download_to_stream(client, cast(IO[bytes], output), **kwargs)
else:
if not overwrite and os.path.isfile(output):
raise ValueError(f"The file '{output}' already exists.")
with open(output, 'wb') as file_handle:
_download_to_stream(client, file_handle, **... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.