text string | label_name string | labels int64 |
|---|---|---|
from django.contrib import admin
from app.apps.core.models import Country, Currency, TimeZone
class ReadOnlyModelAdmin(admin.ModelAdmin):
def has_change_permission(self, request, obj=None):
return False
def has_add_permission(self, request):
return False
def has_delete_permission(self, ... | Python | 1 |
e2 : b'\xc3\xa2', # â
0xe3 : b'\xc3\xa3', # ã
0xe4 : b'\xc3\xa4', # ä
0xe5 : b'\xc3\xa5', # å
0xe6 : b'\xc3\xa6', # æ
0xe7 : b'\xc3\xa7', # ç
0xe8 : b'\xc3\xa8', # è
0xe9 : b'\xc3\xa9', # é
0xea : b'\xc3\xaa', # ê
... | Python | 1 |
"Initialize project in current directory. This option is deprecated and is present only for historical reasons. Prefer the 'import' command instead",
),
] = False,
):
if ctx.invoked_subcommand is None:
zp = Zp()
dirname = os.path.basename(os.getcwd())
sel = None
if dir:
... | Python | 1 |
u64,
pub rsp: u64,
pub rbp: u64,
pub r8: u64,
pub r9: u64,
pub r10: u64,
pub r11: u64,
pub r12: u64,
pub r13: u64,
pub r14: u64,
pub r15: u64,
pub rip: u64,
pub rflags: u64,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct kvm_lapic_state {
pub regs: [::std::os::... | Rust | 0 |
");
assert_eq!(reader.file_path(), Some(Path::new("1byte")));
assert_eq!(reader.read(&mut buf).unwrap(), 1);
assert_eq!(&buf, b"2");
assert_eq!(reader.file_path(), Some(Path::new("2byte")));
}
#[test]
fn fails_on_file_error() {
let strs = &["1byte", "2byte", "404"... | Rust | 0 |
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkCommonDataModel import (
vtkPlane,
vtkPointSet
)
from vtkmodules.vtkFiltersGeneral import vtkTableBasedClipDataSet
# Create a sphere source
sphere_source = vtkSphereSource()
sphere_source.SetRadius(1.0)
sphere_source.SetThetaResolution... | Python | 1 |
"\u{FB77}"]),
// ARABIC LETTER DYEH
('\u{0684}', ["\u{FB72}", "\u{FB74}", "\u{FB75}", "\u{FB73}"]),
// ARABIC LETTER TCHEH
('\u{0686}', ["\u{FB7A}", "\u{FB7C}", "\u{FB7D}", "\u{FB7B}"]),
// ARABIC LETTER TCHEHEH
('\u{0687}', ["\u{FB7E}", "\u{FB80}", "\u{FB81}", "\u{FB7F}"]),
// ARABIC LETTE... | Rust | 0 |
R {
#[doc = "Bit 0 - Read pending status of interrupt for event KEYSLOT_PUSHED"]
#[inline(always)]
pub fn keyslot_pushed(&self) -> KEYSLOT_PUSHED_R {
KEYSLOT_PUSHED_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Read pending status of interrupt for event KEYSLOT_REVOKED"]
#[inline(al... | Rust | 0 |
parse_component_arguments("gridVisible: bool, selectedDate DateTime, minimumDate: DateTime"),
Err(ComponentParseError::WhiteSpaceInComponentName(1, "selectedDate DateTime".to_string()))
);
}
#[test]
fn test_xml_get_item() {
// <a>
// <b/>
// <c/>
// <d/>
// <e/>
... | Rust | 0 |
pub fn sram_0a_rme(&mut self) -> SRAM_0A_RME_W {
SRAM_0A_RME_W { w: self }
}
#[doc = "Bits 2:5 - Read-Write margin Input for Left Channel 8KB FIFO"]
#[inline(always)]
pub fn sram_0a_rm(&mut self) -> SRAM_0A_RM_W {
SRAM_0A_RM_W { w: self }
}
#[doc = "Bit 6 - Test pin to bypass se... | Rust | 0 |
import time
import zlib
def loads(texts):
ll=True
ti=0
xi=0
yi=0
a=[]
ttt=texts.split(";")
ti=len(ttt)
for t in range(ti):
yyy=ttt[t].split("\n")
yi=len(yyy)
for y in range(yi):
xxx=yyy[y].split(",")
xi=len(xxx)
if ll:
... | Python | 1 |
human readable formats the `Display` and `FromStr` interfaces are
//! used. Otherwise all values are serialized in the same format (apart
//! from the newtype wrapping) as a tuple of two values:
//!
//! - `tag: u8`:
//! - `0x00...0x20`: IPv4 with network length `tag`
//! - `0x40...0xc0`: IPv6 with network length `... | Rust | 0 |
)
targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2) # append anchor indices
g = 0.5 # bias
off = torch.tensor(
[
[0, 0],
[1, 0],
[0, 1],
[-1, 0],
[0, -1], # j,k,l,m
# [... | Python | 1 |
(csrc).to_bytes().to_vec()).unwrap();
let mut p = Parser::new(&src);
let pkg: ast::Package = p.parse_file(fname).into();
Box::new(pkg)
}
#[no_mangle]
pub extern "C" fn flux_ast_format(
ast_pkg: &ast::Package,
out: &mut flux_buffer_t,
) -> Option<Box<ErrorHandle>> {
let mut out_str = String::new... | Rust | 0 |
#
dp_dict['body_uv_ann_labels'] = np.array(All_labels).astype(np.int32)
dp_dict['body_uv_ann_weights'] = np.array(All_Weights).astype(np.float32)
#
##########################
dp_dict['body_uv_X_points'] = X_points.astype(np.float32)
dp_dict['body_uv_Y_points'] = Y_points.astype(np.float32)
d... | Python | 1 |
rt_eq!(arr, [1, 2, 3, 4, 7, 10, 24]);
}
}
use super::{
Object,
Objects,
};
#[derive(Debug, Clone, PartialEq)]
pub struct ReturnO {
value: Box<Objects>,
}
impl Object for ReturnO {
fn string(&self) -> String {
self.value.clone().string()
}
}
impl ReturnO {
pub fn new(value: Box<Objects>) -> Box<Ob... | Rust | 0 |
// fn extract_token(headers: &HeaderMap) -> Option<&str> {
// headers.get("Authorization")?.to_str().ok();
// let token = token
// .map(|s| s.replace("Bearer ", ""))
// .unwrap_or_else(|| "".to_string());
// let claims = decode_jws_compact_with_config::<String>(&token, &self.config.authn)?.... | Rust | 0 |
Visitor;
impl<'de> Visitor<'de> for ScalarVisitor {
type Value = Scalar;
fn expecting(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
formatter.write_str("a valid point in Edwards y + sign format")
}
fn visit_seq<A>(self,... | Rust | 0 |
main_tensor = pil_to_tensor(pil_img)
all_tensors = [main_tensor] + hidden_tensors
else:
if hidden_tensors:
main_tensor = hidden_tensors.pop(0)
all_tensors = [main_tensor] + hidden_tensors
log_lines.append("- **Using first embedded image ... | Python | 1 |
s://docs.rs/lv2rs-midi) crates, which
//! provide general data exchange and MIDI messages.
//!
//! ## What is supported, what isn't?
//!
//! Currently 4 out of 22 [official and stable LV2 specifications](http://lv2plug.in/ns/) are
//! supported. These are:
//!
//! * Atom
//! * LV2
//! * MIDI
//! * URID
//!
//! This i... | Rust | 0 |
from llmebench.datasets import AdultDataset
from llmebench.models import AzureModel
from llmebench.tasks import AdultTask
def metadata():
return {
"author": "Mohamed Bayan Kmainasi, Rakif Khan, Ali Ezzat Shahroor, Boushra Bendou, Maram Hasanain, and Firoj Alam",
"affiliation": "Arabic Language Tec... | Python | 1 |
let (Some(out), Some(err)) = (out, err) {
// Termination condition: "until read() returns all-empty data, which marks EOF."
let done = out.is_empty() && err.is_empty();
if !done {
// This is pretty noisy, so only trace if we have data
trace!("[{}] read out={} err={}", id... | Rust | 0 |
ttons and labels
# First Row Label
make_label(pi_hostname, 32, 30, 48, tron_inverse)
# Second Row buttons 3 and 4
make_button(" X on TFT", 30, 105, 55, 210, tron_light)
make_button(" X on HDMI", 260, 105, 55, 210, tron_light)
# Third Row buttons 5 and 6
make_button(" Terminal", 30, 180, 55, 210, tron_light)
mak... | Python | 1 |
from __future__ import annotations
import abc
import logging
from typing import TYPE_CHECKING, ClassVar, Dict, Iterable, Tuple, Any, Optional, Union, TypeGuard
from worlds.LauncherComponents import Component, SuffixIdentifier, Type, components
if TYPE_CHECKING:
from SNIClient import SNIContext
component = Compo... | Python | 1 |
al_sym[0].unit_cell().parameters()[5]), file=out)
print(file=out)
def graphviz_pg_graph(self, out=None):
if out==None:
out=sys.stdout
print("digraph f { ", file=out)
print("rankdir=LR", file=out)
for pg in self.pg_graph.graph.node_objects:
for next_pg in self.pg_graph.graph.edge_ob... | Python | 1 |
ode [style=none] (51) at (5.0, 1.5) {0.500};
\\node [style=none] (56) at (7.5, -0.5) {Rz(0.1)};
\\node [style=none] (61) at (10.0, -0.5) {H};
\\node [style=none] (65) at (0.0, -1.5) {0};
\\node [style=none] (69) at (2.5, -1.5) {0};
\\node [style=none] (73) at (7.5, -1.5) {0};
\\node [style=none] (77) at (10.0, -1.5) {0... | Python | 1 |
_mangle]
pub fn open_image(canvas: HtmlCanvasElement, ctx: CanvasRenderingContext2d) -> PhotonImage {
let imgdata = get_image_data(&canvas, &ctx);
let raw_pixels = to_raw_pixels(imgdata);
return PhotonImage {raw_pixels: raw_pixels, width: canvas.width(), height: canvas.height() }
}
/// Convert ImageData to... | Rust | 0 |
pe::RsString ))
| do_parse!(
sp >> tag!("str") >>
(Tpe::RsStr ))
| do_parse!(
sp >> tag!("bool") >>
(Tpe::Bool ))
));
named!(pub tpe_spes<TpeSpes>,
do_parse!(
sp >> tpe_k: tpe >>
generic_item_k: opt!(do_parse!(sp >> res: generic_item >> (... | Rust | 0 |
h = "to_u64")]
pub total_score: u64,
#[serde(deserialize_with = "to_u32")]
pub pp_rank: u32,
#[serde(deserialize_with = "to_f32")]
pub level: f32,
#[serde(deserialize_with = "to_f32")]
pub pp_raw: f32,
#[serde(deserialize_with = "to_f32")]
pub accuracy: f32,
#[serde(alias = "coun... | Rust | 0 |
BigIntStr, b: usize, c: usize) -> TestResult {
let (ar, ag) = a.parse();
if ar <= 0 || b <= 0 || c <= 0 || b == c {
return TestResult::discard()
}
let (b, c) = order_asc(b, c);
let bg = ref_via_hex(b);
let cg = ref_via_hex(c);
let dr = (&ar * c) + b;
let dg = (&ag * &cg) + &bg;
... | Rust | 0 |
import os
from dataclasses import dataclass
from logging import getLogger
from typing import Dict, List, Optional, Tuple
logger = getLogger("Wine")
lutris_runtime_paths = [os.path.expanduser("~/.local/share/lutris")]
__lutris_runtime: str = None
__lutris_wine: str = None
def find_lutris() -> Tuple[str, str]:
g... | Python | 1 |
after_Encoder_Bottleneck = []
self.after_Decoder_UpBlock1_3 = []
self.after_Decoder_UpBlock1_6 = []
for i, real_B in enumerate(self.testB_loader):
real_B = real_B.to(self.device)
fake_B2A, _, fake_B2A_heatmap = self.genB2A(real_B)
fake_B2A2B, _, fake_B2A2B_hea... | Python | 1 |
ad_stats['uploaded_files'].append(self.FileMd5(file_path))
self._save_upload_stats()
# logging.info("恶意文件上报成功: {}".format(file_path))
return True
else:
# logging.error("恶意文件上报失败 {}: HTTP {}".format(file_p... | Python | 1 |
binary.push(45); /* Ascii - */
for i in 0..4 {
binary.push(99 + i); /* Ascii c .. */
}
binary.push(45); /* Ascii - */
for _ in 0..12 {
binary.push(57); /* Ascii 9 */
}
let mut cursor = Cursor::new(&binary);
assert_eq!(read_uuid_str_d... | Rust | 0 |
Value,
arg_type: ir::Type,
) -> ir::Value {
if arg_type == I64 {
let (arg_lo, arg_hi) = pos.ins().isplit(arg);
let arg = pos.ins().scalar_to_vector(I32X4, arg_lo);
let arg = pos.ins().insertlane(arg, arg_hi, 1);
let arg = pos.ins().raw_bitcast(I64X2, arg);
arg
} else ... | Rust | 0 |
px; }
.news-content { padding-right: 45px; }
.news-item { gap: 8px; }
.new-item { gap: 8px; }
.news-number { width: 20px; height: 20px; font-size: 12px; }
.save-buttons {
position: static;
margin-bott... | Python | 1 |
for F {
#[inline]
fn from(other: u8) -> Self {
F(other)
}
}
impl ::core::fmt::Display for F {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for F {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt... | Rust | 0 |
2(actual_result.limbs.as_mut_ptr(), a.limbs.as_ptr());
}
assert_limbs_are_equal(ops, &actual_result.limbs, &r.limbs);
Ok(())
})
}
// There is no `nistz256_neg` on other targets.
#[cfg(target_arch = "x86_64")]
#[test]
fn p256_elem_neg_test() {
pre... | Rust | 0 |
import torch
from torchvision import datasets, transforms
from torch.utils.data import Subset
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
import os
####绘图函数已被注释,可以自己重新打开
# 设定参数
train_per_class = 500
test_per_class = 300
# 加载 MNIST 原始数据集
transform = transforms.ToTensor()... | Python | 1 |
, key: &str, value: T) -> RedisResult<f64> {
// self.run_command::<f64>("INCRBYFLOAT", vec![key, &*value.to_string()])
// }
// pub fn strlen(&mut self, key: &str) -> RedisResult<i32> {
// self.run_command::<i32>("STRLEN", vec![key])
// }
// pub fn keys(&mut self, pattern: &str) -> Redi... | Rust | 0 |
signatures for multiple images in parallel.
/// ## Parameters
/// * images: Vector of input images of CV_8U type.
/// * signatures: Vector of computed signatures.
fn compute_signatures(&self, images: &core::Vector::<core::Mat>, signatures: &mut core::Vector::<core::Mat>) -> Result<()> {
unsafe { sys::cv_xfeature... | Rust | 0 |
2 for ': '
else:
# By default, NumPy arrays print with linewidth=76. `n` is
# the indent at which a line begins printing, so it is subtracted
# from the default to avoid exceeding 76 characters total.
# `edgeitems` is the number of elements to include before and after
# ellip... | Python | 1 |
for x in &mut buf {
*x = rng.sample(&distr);
}
assert_eq!(buf, expected);
}
test_samples(NormalInverseGaussian::new(2.0, 1.0).unwrap(), 0f32, &[
0.6568966, 1.3744819, 2.216063, 0.11488572,
]);
test_samples(NormalInverseGaussian::new(2... | Rust | 0 |
};
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Comparison {
// Total number of unique lines in the left
pub lines_in_left: usize,
// Number of unique lines in both left and right
pub lines_in_both: usize,
// Total number of unique lines in the right
pub lines_in_right: usize,
}
... | Rust | 0 |
t MyAdd<Rhs=Self> { fn add(&self, other: &Rhs) -> Self; }
impl MyAdd for i32 {
fn add(&self, other: &i32) -> i32 { *self + *other }
}
fn main() {
let x: i32 = 5;
let y = x as MyAdd<i32>;
//~^ ERROR E0038
//~| ERROR cast to unsized type: `i32` as `dyn MyAdd<i32>`
}
<gh_stars>0
use byteorder::{Litt... | Rust | 0 |
ed() && packet.is_to(self.gateway_addr) {
let ack = Packet::ack_from(&packet);
self.rfm.send(&mut ack.as_bytes())?;
}
Ok(packet.message())
}
fn send(&mut self, data: Vec<u8>, to: u8) -> Result<()> {
let packet = Packet::new(self.gateway_addr, to, data, false);
... | Rust | 0 |
"""
Точка входа в приложение
"""
from main import main
if __name__ == '__main__':
main() | Python | 1 |
ount: u32 = rows
.filter_map(|result| result.ok())
.next()
.ok_or_else(|| warp::reject::custom(Error::DatabaseFailedInternally))?;
// Return
#[derive(Debug, Deserialize, Serialize)]
struct Response {
status_code: u16,
member_count: u32,
}
let response =
... | Rust | 0 |
(ColorType::Red, CardType::Number(2)),
UnoCard::new(ColorType::Yellow, CardType::Skipcard),
UnoCard::new(ColorType::Blue, CardType::Reversecard)]);
assert_eq!(new_player.show_cards().len(),3);
}<reponame>gluwa/creditcoin<gh_stars>1-10
u... | Rust | 0 |
# -*- coding: utf-8 -*-
'''
Script: deploy_det_video.py
脚本名称:deploy_det_video.py
Description:
This script runs a real-time object detection application on an embedded device.
It uses a pipeline to capture video frames, performs inference using a pre-trained Kmodel,
and displays the detection results (bound... | Python | 1 |
UrlsMGPREuGkBih8+o85ii6D+cuCiVtus3f5c78Cir80zLIr
Z0wWvEAjciEvml00DWaA+JIaOrWwvXySaOzFGpCqC9SQjao379bvn9P3b7kVZsy6zBfHqm
bNEJUOuhBZaY8Okz36chh1xqh4sz7m3nsZ3GYGcvM+3mvRY72QnqsQEG0Sp1XYIn2bHa29
tqp7CG9X8J6dqMcPeoPRDWIX9gw7EPl/M0LP6xgewGJ9bgxwle6Mnr9kNITIswjAJqrLec
zx7dfixjAPc42ADqrw/tEdFQcSqxigcfJNKO1LbDBjh+Hk/cSBou2PoxbI... | Python | 1 |
import os
########################################################################################################################
# General Settings
ET_ROOT = os.environ["ET_ROOT"]
ET_DATA = os.environ["ET_DATA"] if "ET_DATA" in os.environ else None
ET_LOGS = os.environ["ET_LOGS"] if "ET_LOGS" in os.environ else Non... | Python | 1 |
self.interval_x.contains(p[0])
&& self.interval_y.contains(p[1])
&& self.interval_z.contains(p[2])
}
}
impl<'a, T: Float, P> Absorb<P> for &'a mut BBox<T>
where
P: Into<[T; 3]>,
{
type Output = &'a mut BBox<T>;
fn absorb(self, p: P) -> Self::Output {
let p = p.... | Rust | 0 |
tion if span_end is None else span_end,
)
raise ParserSyntaxError(
message,
source=self.source,
span=span,
)
@contextlib.contextmanager
def enclosing_tokens(
self, open_token: str, close_token: str, *, around: str
) -> Iterator[None]:
... | Python | 1 |
ernel.console_command(
"gpio_set",
help=_("gpio_set <port> <value>")
+ "\n"
+ _("Sets a GPIO port on the RPI to a given value"),
input_type=None,
output_type=None,
)
def gpio_set(
command,
channel,
... | Python | 1 |
SCREEN,
HPDF_BM_OVERLAY,
HPDF_BM_DARKEN,
HPDF_BM_LIGHTEN,
HPDF_BM_COLOR_DODGE,
HPDF_BM_COLOR_BUM,
HPDF_BM_HARD_LIGHT,
HPDF_BM_SOFT_LIGHT,
HPDF_BM_DIFFERENCE,
HPDF_BM_EXCLUSHON,
HPDF_BM_EOF
}
/*----- slide show -----------------------------------------------------------*/
#[repr... | Rust | 0 |
tr = "contact_last_updated_timestamp";
/// public static final [DISPLAY_NAME](https://developer.android.com/reference/android/provider/ContactsContract.ContactsColumns.html#DISPLAY_NAME)
pub const DISPLAY_NAME : &'static str = "display_name";
/// public static final [HAS_PHONE_NUMBER](https://... | Rust | 0 |
GroupEntity { entities: Vec::new() }
}
}
fn pointentity_from_dxf_point(point: &Point) -> PointEntity {
PointEntity {
x: point.x as f32,
y: point.y as f32,
z: point.z as f32,
r: 0xcc,
g: 0xcc,
b: 0xcc
}
}
fn polylineentity_from_dxf_polyline(polyline:... | Rust | 0 |
ader_keys,
PeriphManagerBase.mboard_eeprom_magic)
self._check_data(
data,
magic=PeriphManagerBase.mboard_eeprom_magic,
eeprom_version=3,
mcu_flags=b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
pid=0xDEAD,
... | Python | 1 |
.lower() in ['apply suggested improvements', '', 'no suggestion']:
continue
# Remove if explanation or reasoning is mostly code (e.g., >50% non-alpha)
if len(explanation) > 20 and (len(re.sub(r'[^a-zA-Z]', '', explanation)) / len(explanation)) < 0.3:
continue
... | Python | 1 |
mnemonic,
Mnemonic::parse(mnemonic_str).unwrap(),
"failed vector: {}",
mnemonic_str
);
assert_eq!(
&seed[..],
&mnemonic.to_seed("TREZOR")[..],
"failed vector: {}",
mnemonic_str
);
assert_eq!(&entropy, &mnemonic.to_entropy(), "failed vector: {}", mnemonic_str);
... | Rust | 0 |
"""Test fixtures for SimpleFIN."""
from collections.abc import Generator
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from simplefin4py import FinancialData
from simplefin4py.exceptions import SimpleFinInvalidClaimTokenError
from homeassistant.components.simplefin import CONF_ACCESS_URL
from h... | Python | 1 |
tore_true")
return p.parse_args()
def main():
args = parse_args()
print_banner()
system = platform.system()
timestamp = datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
out_file = args.out_file
if not out_file:
out_file = f"logs_{system}_{timestamp}.{args.output}"
print(f"[+] Pla... | Python | 1 |
intersection<T>(
s: &Section<T>,
p1: (T, T),
p2: (T, T),
p3: (T, T),
p4: (T, T),
) -> Result<(T, T), ArmsErr<T>>
where
T: Float
+ NumCast
+ std::cmp::PartialOrd
+ SampleUniform
+ std::marker::Sync
+ std::marker::Send
+ std::fmt::Display
+ s... | Rust | 0 |
PU = 2,
/// See [`VkPhysicalDeviceType`](https://www.khronos.org/registry/vulkan/specs/1.0-extensions/html/vkspec.html#VkPhysicalDeviceType)
const VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU = 3,
/// See [`VkPhysicalDeviceType`](https://www.khronos.org/registry/vulkan/specs/1.0-extensions/html/vkspec.html#VkPhysi... | Rust | 0 |
::*;
audits
.filter(addr.eq(format!("{}", a)))
.order_by(ts.desc())
.limit(1)
.load::<Audit>(&conn)
.unwrap()
};
if audits.len() > 0 {
let audit = &audits[0];
match audit.state {
... | Rust | 0 |
1" ON (1) JOIN "t2" ON (1) JOIN "t3" ON (1) JOIN "t4" ON (1) JOIN "t5" ON (1)
JOIN "t6" ON (1) JOIN "t7" ON (1) JOIN "t8" ON (1) JOIN "t9" ON (1) JOIN "t10" ON (1)
JOIN "t11" ON (1) JOIN "t12" ON (1) JOIN "t13" ON (1) JOIN "t14" ON (1) JOIN "t15" ON (1)
JOIN "t16" ON (1) JOIN "t17" O... | Rust | 0 |
import numpy as np
from ultralytics import YOLO
def detect_objects(model, image):
results = model(image,conf=0.35)
detections = []
for result in results:
for box, cls in zip(result.boxes.xywh, result.boxes.cls):
x, y, w, h = box.cpu().numpy()
class_id = int(cls.cpu().... | Python | 1 |
order
///
/// The default order of axes in ArrayFire is axis with smallest distance
/// between adjacent elements towards an axis with highest distance between
/// adjacent elements.
///
///# Parameters
///
/// - `input` is the input Array
/// - `dims` is the target(output) dimensions
///
///# Return Values
///
/// Ar... | Rust | 0 |
: C, new_client: N)
where
C: Credentials,
N: NewService<(), Service = S>,
S: GrpcService<BoxBody>,
S::ResponseBody: Send + Sync + 'static,
<S::ResponseBody as Body>::Data: Send,
<S::ResponseBody as Body>::Error: Into<Error> + Send,
{
debug!("Identity daemo... | Rust | 0 |
return True
else:
print("The user doesn't exist in the database")
return False
def delete_user_favorite_movie(self, user_id, movie_id):
"""
Delete a movie from an user's favorite list from table user_favorites
:param us... | Python | 1 |
h_size))
img = rearrange(
x, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=patch_size, pw=patch_size
)
h_len = (h + (patch_size // 2)) // patch_size
w_len = (w + (patch_size // 2)) // patch_size
img_ids = torch.zeros((h_len, w_len, 3), device=x.device, dtype=x.dtype)... | Python | 1 |
# Copyright (C) 2016 KillerInstinct
#
# 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 version.
#
# This program is distributed in... | Python | 1 |
"""
old_means, old_logvars = self.old_policy_model.policy(obs)
old_means.stop_gradient = True
old_logvars.stop_gradient = True
old_logprob = self._calc_logprob(actions, old_means, old_logvars)
means, logvars = self.model.policy(obs)
logprob = self._calc_logprob(actions,... | Python | 1 |
# Copyright(C) 2022-2023 Intel Corporation
# SPDX - License - Identifier: Apache - 2.0
import gi
gi.require_version("Gimp", "3.0")
gi.require_version("GimpUi", "3.0")
gi.require_version("Gtk", "3.0")
from gi.repository import Gimp, GimpUi, GObject, GLib, Gio, Gtk
import gettext
_ = gettext.gettext
def show_dialog(m... | Python | 1 |
from chessboard import ChessBoard
# Class representing the game logic
class Game:
def __init__(self):
self.board = ChessBoard() # Create the chessboard
self.turn = 'white' # White player starts
# Placeholder to switch turns between players
def switch_turn(self):
if self.turn == '... | Python | 1 |
_path, &results_path, |abs_path| {
f().and_then(|result| {
//Result was computed; serialize it back
save_results::<T>(&abs_path, &result).and(Ok(abs_path))
})
})?;
load_cached_results::<T>(&abs_path)
}
/// Identical to `cache_object_computation` except this is read-only... | Rust | 0 |
ann_file = prefix + "_map_train.txt"
else:
ann_file = prefix + "_map_val.txt"
dataset = IN22KDATASET(config.DATA.DATA_PATH, ann_file, transform)
nb_classes = 21841
elif config.DATA.DATASET == 'other':
prefix = 'train' if is_train else 'val'
root = os.path.j... | Python | 1 |
# Write a Python code to remove all characters except a
# Sample String : 'exercises'
# Expected Result : 'eee' (Removed all characters except special character : e)
sample_string = input("enter any string")
result = ''.join(char for char in sample_string if char == 'a')
print(result) | Python | 1 |
);
println!("File: {}", path);
println!(" Part 1: {}", solve(&1, &parsed));
println!(" Part 2: {}", solve(&2, &parsed));
}
fn main() {
env::args().skip(1).for_each(|x| output(&x));
}
use std::fmt::{self, Display};
use nalgebra::Vector3;
pub struct HalfSpace {
pub v: Vector3<f32>,
pub d: f3... | Rust | 0 |
when compiling the program using the msvc compiler
::std::thread::Builder::new()
.stack_size(2 * 1024 * 1024)
.spawn(|| {
init_env_logger();
let matches = App::new("gluon")
.about("Executes gluon programs")
.arg(Arg::with_name("INPUT")
... | Rust | 0 |
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
def execute():
fields = {
"Company": [
{
"fieldname": "auto_prescribe_items_on_patient_encounter",
"label": "Auto Prescribe Items on Patient Encounter",
... | Python | 1 |
# Copyright (c) 2024-Present
# Author: Jiawei Zhang <jiawei@ifmlab.org>
# Affiliation: IFM Lab, UC Davis
######################
# Statistics Library #
######################
"""
This module provides the libraries of "statistics" that can be used to build the RPN model within the tinyBIG toolkit.
## Statistics Libra... | Python | 1 |
# coding=utf-8
# *** WARNING: this file was generated by pulumigen. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import builtins as _builtins
from ... import _utilities
import typing
# Export this package's modules as members:
from ._enums import *
from .Binding import *
from .B... | Python | 1 |
})
}
}
fn commit(self) {
// only log the error, indexer store commit failure should not causing the thread to panic entirely.
if let Err(err) = self.batch.commit() {
error!("indexer db failed to commit batch, error: {:?}", err)
}
}
}
#[cfg(test)]
mod tests {
... | Rust | 0 |
sl<C, T>(self, exec: C, server: Arc<Octane>) -> Result<()>
where
T: Future + Send,
C: FnOnce(SslStream<TcpStream>, Arc<Octane>) -> T + Send + 'static + Copy,
{
let mut ssl_listener = self.socket;
let acceptor = crate::tls::openssl::acceptor(&server.settings)?;
while let S... | Rust | 0 |
sin(2 * np.pi * df_all[k] / period)
# Add grouped statistics as used in lightGBM by winners
df_tmp = df_all[["date", "d", "state_id", "sales"]].copy()
df_tmp["idx"] = pd.to_datetime(df_tmp["date"])
df_tmp["idx"] = (df_tmp["idx"] - df_tmp["idx"].min()).dt.days + 1
# mask out the sales during the tes... | Python | 1 |
لديه إجابات مسجلة!")
return False
await db.d1.execute("DELETE FROM Users WHERE user_id=?", (user_id,))
st.success("تم حذف المستخدم بنجاح")
return True
except Exception as e:
st.error(f"حدث خطأ أثناء الحذف: {str(e)}")
return False
async def manage_survey... | Python | 1 |
for j in cur_gts]
for i, vid in enumerate(self.gt_vids):
_p = [tokenize_preds[j] for j in range(p_spliter[i],p_spliter[i+1])]
self.preds[vid] = {"timestamps":times[i], "sentences":_p}
for n in range(n_ref):
if vid not in self.gts[n]: continue
... | Python | 1 |
t c = 1 << 60 as u64;
let len = encode_varint_64(&mut v, c);
let mut s = Slice::from(&v[..]);
let v = super::decode_varint_64_slice(&mut s).expect("shouldn't be None");
assert_eq!(v, c);
assert_eq!(s.len(), 10 - len);
}
#[test]
fn prefix_length_slice() {
let ... | Rust | 0 |
utput.return_value = "\n".join(
[
"41ceaeab58473416bb79680ab21211764e6f1908",
"a4d0daa91c25a51ca95182301e503c020900dafe",
"05906c81f5778a543dfab14e77231db0a99bae24",
]
)
gitrange = "41ceaeab58473416bb79680ab21211764e6f1908..05906c81... | Python | 1 |
m(s)))
}
}
}
// cp is probably gsutil's most complicated subcommand, so we only implement
// a bare minimum
pub async fn cmd(ctx: &util::RequestContext, args: Args) -> Result<(), Error> {
use std::fs;
let src = DataPath::try_from(args.src_url)?;
let dst = DataPath::try_from(args.dest_url)?;
... | Rust | 0 |
pub fn get<'a>() -> MutexGuard<'a, Self> {
SECURE_CHANNEL_CTX.lock().unwrap()
}
/// Convert client short-term public key into session hash map key.
fn get_session_key(public_key: &[u8]) -> Result<sodalite::BoxPublicKey> {
if public_key.len() != sodalite::BOX_PUBLIC_KEY_LEN {
re... | Rust | 0 |
end, b.end))
}
fn range_high(a: &Range<isize>, b: &Range<isize>) -> Range<isize> {
(max(a.start, b.end))..(a.end)
}
// Return an iterator of non-overlapping cuboids that cover the points
// in the base cuboid but not the other cuboid.
fn cube_diff(base: &Cuboid, other: &Cuboid) -> impl Iterator<Item=Cuboid> {
... | Rust | 0 |
_sql::*;
use rocket::State;
use rocket_contrib::json::Json;
use rocket_okapi::openapi;
use crate::guards::*;
use crate::responses::errors::*;
use crate::responses::tm_names::*;
use crate::utils;
#[openapi]
#[get("/tms/names")]
pub fn get_tm_name_all(
sql: State<PkmnapiSQL>,
_rate_limit: RateLimit,
access_... | Rust | 0 |
/// Should this character be ignored in steps after X9?
///
/// <http://www.unicode.org/reports/tr9/#X9>
pub fn removed_by_x9(class: BidiClass) -> bool {
matches!(class, RLE | LRE | RLO | LRO | PDF | BN)
}
// For use as a predicate for `position` / `rposition`
pub fn not_removed_by_x9(class: &BidiClass) -> bool {... | Rust | 0 |
is not easier (early stop) to optimize free const next time
my_programs = Prog.VectPrograms(batch_size=batch_size, max_time_step=test_program_length, library=my_lib)
my_programs.set_programs(test_program_idx)
# Run tasks
t0 = time.perf_counter()
Exec.BatchFreeConstOpti(progs = m... | Python | 1 |
policy for this timed text track
# It should generate a key file with the Unix timestamp of the present time
now = datetime(2018, 8, 8, tzinfo=baseTimezone.utc)
with mock.patch.object(timezone, "now", return_value=now), mock.patch(
"datetime.datetime"
) as mock_dt:
... | Python | 1 |
is(predicted_rgb, -1, 0)[None, ...]
psnr = self.psnr(gt_rgb, predicted_rgb)
ssim = self.ssim(gt_rgb, predicted_rgb)
lpips = self.lpips(gt_rgb, predicted_rgb)
# all of these metrics will be logged as scalars
metrics_dict = {"psnr": float(psnr.item()), "ssim": float(ssim)} # typ... | Python | 1 |
tr_rect.translate(vec2(30, 0))),
tr_inner_corner: to_texture_rect(tr_rect.translate(vec2(45, 0))),
tr_solid: to_texture_rect(tr_rect.translate(vec2(60, 0))),
bl_outer_corner: to_texture_rect(bl_rect),
bl_horz: to_texture_rect(bl_rect.translate(vec2(15, 0))),
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.