text string | label_name string | labels int64 |
|---|---|---|
import copy
import html
import json
import math
import os
import shutil
import time
from wxManager.decrypt.decrypt_dat import batch_decode_image_multiprocessing
from wxManager.log import logger
from wxManager.model import MessageType, Me
from exporter.exporter import ExporterBase, copy_files, decode_audios, get_new_fil... | Python | 1 |
le {}", msg);
},
_ => {}
}
}
pub fn get_file_len(&self) -> u64 {
match self.file.metadata() {
Err(_msg) => {
error!("retrieving file size");
0
},
Ok(md) => {md.len()}
}
}
}// Copyright (c) 202... | Rust | 0 |
# Definición de un diccionario donde claves son números y valores son sus nombres en español
numbers = {1: "uno", 2: "dos", 3: "tres"}
print(numbers[2]) # Imprime el valor asociado a la clave 2: "dos"
# Definición de un diccionario con información personal
information = {"nombre": "Carla",
"Apellido":... | Python | 1 |
from(u64::max_value()) {
return Err(ExitError::OutOfGas)
}
Ok(gas.as_u64())
}
}
pub fn verylowcopy_cost(len: U256) -> Result<u64, ExitError> {
let wordd = len / U256::from(32);
let wordr = len % U256::from(32);
let gas = U256::from(G_VERYLOW).checked_add(
U256::from(G_COPY).checked_mul(
if wordr == U... | Rust | 0 |
se_param.coeff[i] = new_bottom[item][1]
# Step 2:Combine binary op to multi-input eltwise
eltwise_opt_set = []
matched = []
# Get all eltwise_set which can be merged together
for layer_target in eltwise_layer:
eltwise_set = [layer_target]
for layer_find in eltwise_layer:
... | Python | 1 |
mut IDWriteGeometrySink,
figure_end: D2D1_FIGURE_END) {
let this = this as *mut PathfinderGeometrySink;
if figure_end == D2D1_FIGURE_END_CLOSED {
(*this).commands.push(PathEvent::Close)
}
}
unsafe extern "system" fn SetFillMode(_: *mut... | Rust | 0 |
_m(&mut self, mouse_down: Option<MouseDown<E>>, mouse_pressed: bool, mouse: Offset, b: Bounds, ctx: &mut E::Context) {
let g = self.glyphs2(ctx);
let mut cursor = self.cursor.get(ctx);
cursor.fix_boundaries(&*g);
let off = self.scroll.get(ctx);
let mut tpos = mouse - b.off + Off... | Rust | 0 |
, idx]))
return torch.cat(o, 1), internal_outputs
class FullPoseDiscriminator(LinearModel):
def __init__(self, fc_layers, use_dropout, drop_prob, use_ac_func):
if fc_layers[-1] != 1:
msg = 'the neuron count of the last layer must be 1, but got {}'.format(fc_layers[-1])
sys... | Python | 1 |
######################################################################
# region Source Mapping
###################################################################################
###################################################################################
def _find_source_mapping_references(irs: List[Operation... | Python | 1 |
#!/usr/bin/env python
# a fabfile to manange the performance test for unified order project.
# usage: fab -f unified_order_fabfile.py start_jmeter -P -z 30
# author: Jay <smile665@gmail.com>
from fabric.context_managers import cd
from fabric.operations import run, put
from fabric.api import task, env
env.hosts = ['19... | Python | 1 |
"""Data summary operation."""
# Note, these are hardcode for compas!
def data_operation(conversation, parse_text, i, **kwargs):
"""Data summary operation."""
description = conversation.describe.get_dataset_description()
text = f"The data contains information related to <b>{description}</b>.<br><br>"
... | Python | 1 |
.
model.fit(x=train_dataset, epochs=1, steps_per_epoch=10)
weights = model.get_weights()
x_predict = [[1.], [2.], [3.], [4.]]
predict_batch_size = 4
if with_distribution:
predict_batch_size //= with_distribution.num_replicas
predict_dataset = dataset_ops.Datase... | Python | 1 |
(update_) == 0
assert add_[0] == chunks_curr[0]
def test_get_chunks_to_delete_empty() -> None:
chunks_prev = add_item_checksum([], ["url"])
delete_, old_keep_ = get_chunks_to_delete(chunks_prev, chunks_prev, 1)
assert len(delete_) == 0
assert len(old_keep_) == 0
def test_get_chunks_to_delete_no_... | Python | 1 |
max_head_layers = 5
param_names.append("head_layer_size_length")
param_space.append(Integer(1, max_head_layers))
# Optimize individual layer sizes
layer_size_min, layer_size_max = 16, 512
for i in range(max_head_layers):
layer_key ... | Python | 1 |
+ 'static> {
new_dispatch()
}
use portus::ipc;
use portus::Error;
use std::net::UdpSocket;
use std::sync::mpsc;
use portus::Result;
pub struct Socket {
sk: UdpSocket,
outbox_found: mpsc::Sender<std::net::SocketAddr>,
}
impl Socket {
pub fn new(port: u16, outbox_found: mpsc::Sender<std::net::SocketAd... | Rust | 0 |
start(self):
active = Step.get_by_state("A")
inactive = Step.get_by_state('I')
if (active is not None):
active.state = 'D'
active.end = int(time.time())
self.stop_step()
Step.update(**active.__dict__)
if (inactive is not None):
... | Python | 1 |
OTTOM_LEFT: Anchors = Anchors::new(0.0, 0.0, 0.0, 0.0);
pub const BOTTOM_RIGHT: Anchors = Anchors::new(1.0, 1.0, 0.0, 0.0);
pub const CENTER: Anchors = Anchors::new(0.5, 0.5, 0.5, 0.5);
pub const CENTER_BOTTOM: Anchors = Anchors::new(0.5, 0.5, 0.0, 0.0);
pub const CENTER_FULL_HORIZONTAL: Anchors = Ancho... | Rust | 0 |
)).unwrap();
// Fetch the start address of the application RAM.
let mut ram_start = 0u32;
check(nrf::softdevice_app_ram_start_get(&mut ram_start)).unwrap();
// Overwrite some of the default configurations for the BLE stack.
let mut ble_cfg = nrf::ble_cfg_t::default();
check(nrf::sd_ble_cfg_set... | Rust | 0 |
("game_event", &json!({
"game": "RAW_CLIENT_HEALTH",
"event": "HEALTH",
"data": {
"value": health,
}
})).await?;
tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
}
// Cycle digital meter
for value in (0..11).re... | Rust | 0 |
from enum import Enum, auto
class RootAttribute(Enum):
"""
An enum class to represent attributes of a root
...
Methods
-------
get_string_form(sound=None)
Returns the name of the class member
"""
Aorist_I = auto()
Aorist_A = auto()
ProgressiveVowelDrop = auto()
P... | Python | 1 |
import streamlit as st
st.set_page_config(page_title="Car Sales App", layout="wide")
st.switch_page("pages/Home.py")
| Python | 1 |
.to_csv(index=False),
file_name='zebra_heatmap_data.csv'
)
else:
include_routes = st.checkbox(
'Overlay trip shapes?', value=False,
help='This may slow map rendering if there are many distinct '
'shapes to plot.'
)
if include_rou... | Python | 1 |
zh-MINNAN" : "Chinese-Minnan",
"zh-WENZHOU" : "Chinese-Wenzhou",
# ───────────────────────────── Yue-Cantonese variants ───────────────────────────
"ct-NULL" : "Yue-Unknown",
"ct-HK" : "Yue-Hongkong",
"ct-GZ" ... | Python | 1 |
for i in range(1, 11):
if i 2 % == 0:
print(f'') | Python | 1 |
=> x += value,
(Command::West(value), _) | (Command::Forward(value), 270) => x -= value,
(Command::Left(value), _) => angle = (angle - value).rem_euclid(360),
(Command::Right(value), _) => angle = (angle + value).rem_euclid(360),
_ => unreachable!(),
}
}
(x.abs() + y.abs()) as usize
}
fn part_two() -... | Rust | 0 |
stacks = [['Yellow', 'Green', 'Green', 'Blue'], [], [], ['Red', 'Green', 'Blue', 'Yellow'], [], ['Yellow', 'Blue', 'Red', 'Red']]
costs = {0: 1, 1: 5, 2: 6, 3: 7, 4: 7, 5: 5}
min_cost = float('inf')
best_moves = []
def is_sorted():
for stack in stacks:
if len(stack) > 0 and len(set(stack)) != 1:
... | Python | 1 |
to_i(&self) -> u8 {
if self.piece == Piece::Empty {
return 0;
}
let piece: u8 = match self.piece {
Piece::Empty => 0,
Piece::王将 => 1,
Piece::飛車 => 2,
Piece::角行 => 4,
Piece::金将 => 6,
Piece::銀将 => 7,
... | Rust | 0 |
"""
Test suite for different model providers, as specified in tests/config.py.
These tests check that:
- The model providers correctly return a response when run by a simple agent
- The model returns the expected content in its output
"""
import pytest
from deep_researcher.agents.writer_agent import init_writer_agent
... | Python | 1 |
BrowserHandle: HHTMLBrowser,
pub pchMsg: *const ::std::os::raw::c_char,
}
pub const HTML_ShowToolTip_t_k_iCallback: HTML_ShowToolTip_t__bindgen_ty_1 =
HTML_ShowToolTip_t__bindgen_ty_1::k_iCallback;
#[repr(i32)]
#[non_exhaustive]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum HTML_ShowToolTip_t__bindgen_t... | Rust | 0 |
resented by a list of products of polynomials along with its coefficient that is meant to be added together.
///
/// This data structure of the polynomial is a list of list of `(coefficient, DenseMultilinearExtension)`.
/// * Number of products n = `polynomial.products.len()`,
/// * Number of multiplica... | Rust | 0 |
None,
}
}
fn parse_quote(tokens: &[Token]) -> Option<&[Token]> {
match tokens.first() {
Some(Token::Quote) => tokens.get(1..),
_ => None,
}
}
fn parse_dot(tokens: &[Token]) -> Option<&[Token]> {
match tokens.first() {
Some(Token::Ident(s)) if s == "." => tokens.get(1..),
... | Rust | 0 |
}
drop(root_elem);
for node in ptr_to_required_node.values_mut() {
node.set_attribute_ns(ATTRIB_SIGVER, VALUE_SIGVER, ns)
.unwrap();
}
}
/// Remove all elements that do not contain a signature-verified attribute ([`ATTRIB_SIGVER`] in
/// the namespace [`XMLNS_SIGVER`]).
#[cfg(featur... | Rust | 0 |
elanda Caribbean', 'mt': 'in-Netherlands tal-Karibew', 'my': 'ကာရစ်ဘီယံ နယ်သာလန်', 'mzn': 'هلند ِکاراییبی جزایر', 'nb': 'Karibisk Nederland', 'ne': 'क्यारिवियन नेदरल्याण्ड्स', 'nl': 'Caribisch Nederland', 'nn': 'Karibisk Nederland', 'no': 'Karibisk Nederland', 'nqo': 'ߤߏߟߊ߲ߘ ߞߊߙߌߓߋ߫', 'or': 'କାରବିୟନ୍\u200c ନେଦରଲ୍ୟାଣ୍ଡ'... | Python | 1 |
params['task_amount'] = self.task_amount.to_alipay_dict()
else:
params['task_amount'] = self.task_amount
if self.task_desc:
if hasattr(self.task_desc, 'to_alipay_dict'):
params['task_desc'] = self.task_desc.to_alipay_dict()
else:
... | Python | 1 |
中读出程序入口地址
PROCESSOR
.lock()
.add_thread(create_thread(
process,
elf.header.pt2.entry_point() as usize,
None
));
run_first_thread();
}
/// 内核线程需要调用这个函数来退出
fn kernel_thread_exit() {
// 当前线程标记为结束
PROCESSOR.lock().current_thread().as_ref().inner... | Rust | 0 |
Page<A>, cont: &Option<Vec<(String, String)>>)
-> Result<(Vec<Value>, Option<Vec<(String, String)>>)> {
page.request_images(&cont)
}
fn from_value(value: &Value) -> Option<Image> {
let obj = match value.as_object() {
Some(o) => o,
None => return None,
... | Rust | 0 |
_ONLY_OID: &str = "1.2.840.113556.1.4.2207";
#[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"]
pub const LDAP_SEARCH_HINT_INDEX_ONLY_OID_W: &str = "1.2.840.113556.1.4.2207";
#[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"]
pub const LDAP_SEARCH_HINT_REQUIRED_INDEX_OID: &str = "1.2.840.113556.1.4.23... | Rust | 0 |
!("done\n");
}
<reponame>Mr-Byte/Dice
use super::upvalue::UpvalueDescriptor;
use bytes::BufMut as _;
use dice_core::{
bytecode::{instruction::Instruction, Bytecode},
error::{
codes::{TOO_MANY_CONSTANTS, TOO_MANY_UPVALUES},
Error,
},
source::Source,
span::Span,
value::{Symbol, Val... | Rust | 0 |
rror {
// TODO: add error string from bfd's perror-like c api
FormatCheckError,
NullPtrError,
IoError(io::Error),
LinkError,
}
impl From<io::Error> for BFDError {
fn from(error: io::Error) -> Self {
BFDError::IoError(error)
}
}
pub type Error = BFDError;
pub type Result<T> = ::std::result::Result<T... | Rust | 0 |
1):
metric_list.append(calculate_metric_percase(prediction == i, label == i))
if test_save_path is not None:
img_itk = sitk.GetImageFromArray(image.astype(np.float32))
prd_itk = sitk.GetImageFromArray(prediction.astype(np.float32))
lab_itk = sitk.GetImageFromArray(label.astype(np.f... | Python | 1 |
y1) * (x2 + y2)
let u1 = (&this.x * -a) + &this.y;
let u2 = &other.x + &other.y;
let u = u1 * &u2;
// Compute v0 = x1 * y2
let v0 = &other.y * &this.x;
// Compute v1 = x2 * y1
let v1 = &other.x * &this.y;
// Compute C ... | Rust | 0 |
syn::parse_quote!(Self :: #acc_t_param)
}
}
// impl Many {
// pub fn extract_expr(
// &self,
// slf: &rust::Id,
// is_own: IsOwn,
// if_some: impl FnOnce(TokenStream) -> TokenStream,
// if_none: impl FnOnce() -> TokenStream,
// ) -> TokenStream {
// match &se... | Rust | 0 |
\t'); }
(any, _) => { out_string.push(any); }
}
}
// Remove the last character
if out_string.chars().last() == in_string.chars().nth(0) {
out_string.pop();
}
// out_string contains the result
out_string
}
///
/// Parses a bit number (01010b6) as a cell
///
f... | Rust | 0 |
== parent
|| parent == &purity::Ref::Fixed(Purity::Impure)
}
fn inst_polymorphic_fun(sub_fun: &ty::Fun, par_top_fun: &ty::TopFun) -> ty::Fun {
let mut stx = ty::select::SelectCtx::new(sub_fun.pvars(), sub_fun.tvars());
stx.add_evidence(sub_fun.ret(), par_top_fun.ret());
stx.add_evidence_purity(su... | Rust | 0 |
ef<Path>>(&self, path: P) -> Result<()> {
let mut file = BufWriter::new(File::create(path)?);
// Write StateTable
self.state_table.write_binary(&mut file)?;
Ok(())
}
}
#[derive(Debug)]
pub struct ComposeFstOp<W, F1, F2, B1, B2, M1, M2, CFB>
where
W: Semiring,
F1: Fst<W>,
... | Rust | 0 |
ng(tokens, exclude_list):
n = len(tokens)
word_start = [int(token not in exclude_list) for token in tokens]
word_idx = list(accumulate(word_start))
token_to_word = {i: word_idx[i] for i in range(n)}
return token_to_word
def extract_hard_alignment(attn, src_sent, tgt_sent, pad, eos):
tgt_valid ... | Python | 1 |
mport,
metis,
};
// A Example for erc20 contract
#[ink(storage)]
#[import(erc20, capped)]
pub struct Erc20Capped {
erc20: erc20::Data<Erc20Capped>,
capped: capped::Data<Erc20Capped>,
}
#[cfg(not(feature = "ink-as-dependency"))]
impl erc20::hookable::Impl<Erc20Ca... | Rust | 0 |
import json
import logging
import os
from datetime import datetime
from functools import wraps
from api_module import main_api as api
from entity_module import Config
from exception import KnownException, SendInitException
from send_module import util as sendutil
from common_module.util import is_set
THIS_PATH = os.p... | Python | 1 |
import os
import numpy as np
import cv2
from pathlib import Path
from tqdm import tqdm
def write_point_cloud(ply_filename, points):
formatted_points = []
for point in points:
formatted_points.append("%f %f %f %d %d %d 0\n" % (point[0], point[1], point[2], point[3], point[4], point[5]))
out_file =... | Python | 1 |
#coding=utf-8
# ============================
# Programa: EntradaDatos
# Contacto: Juan Dario Rodas - juand.rodasm@upb.edu.co
# Propósito:
# ----------
# - Demostrar el funcionamiento básico de la captura de datos desde la consola, utilizando el método input().
# - Demostrar el cambio de tipo de datos desde... | Python | 1 |
]),
(TxtCtl.SetColor, 0x0),
'只能放弃了。',
TxtCtl.Enter,
),
)
CloseMessageWindow()
OP_56(0x00)
FadeIn(300, 0)
PlaySE(44, 0x00, 0x64)
OP_6F(0x000E, 60)
OP_70(0x000E, 0)
def _loc_118B(): pass
label('loc_118B')
Jump('loc_11BF')
def _lo... | Python | 1 |
stance(data, np.ndarray):
shape = data.shape
else:
shape = ()
if dtype is None:
if data is None:
raise Exception('dtype or data must be provided')
if isinstance(data, np.ndarray):
... | Python | 1 |
T::decode(s)?,
original: s.to_owned(),
spooky: PhantomData,
})
}
}
impl<T> PartialEq<[u8]> for Decoded<T> {
fn eq(&self, other: &[u8]) -> bool {
self.bytes.eq(&other)
}
}
impl<T> PartialEq<Vec<u8>> for Decoded<T> {
fn eq(&self, other: &Vec<u8>) -> bool {
... | Rust | 0 |
64;
fn next(&mut self) -> Option<u64> {
// Special cases so we can optimise with +2 rather than +1 in the loop below.
if self.prev == 0 {
self.primes.push(2);
self.prev = 2;
return Some(self.prev);
} else if self.prev == 2 {
self.primes.push(3... | Rust | 0 |
CODE_UNKNOWN_FAILURE_1605 = 1605
"""Unknown error"""
CODE_UNKNOWN_FAILURE_1700 = 1700
"""Unknown error"""
CODE_UNSUPPORTED_TIMEZONE = 500
"""The selected timezone is not supported"""
CODE_GENERIC_ERROR = 5000
"""Unknown or generic error"""
CODE_UNKNOWN_FAILURE_5001 = 5001
"""Unkn... | Python | 1 |
($ptr:ident) => {
impl<T, U> Dummy<U> for $ptr<T>
where
T: Dummy<U>,
{
fn dummy_ref(config: &U) -> Self {
$ptr::new(T::dummy_ref(config))
}
}
};
}
container!(Box);
container!(Cell);
container!(RefCell);
container!(Rc);
container!(A... | Rust | 0 |
/// After first mount this function will update the Virtual [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction) and then the real [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction).
/// It works by
///1. Passing the function a new [rust_... | Rust | 0 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | Python | 1 |
variant as u8 != 0
}
}
#[doc = "Reader of field `ILIM2_F`"]
pub type ILIM2_F_R = crate::R<bool, ILIM2_F_A>;
impl ILIM2_F_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ILIM2_F_A {
match self.bits {
false => ILIM2_F_A::THIS_INTERRUPT_SOURC,
... | Rust | 0 |
b: 1:1-1:2 => B::A(
1:1-1:2,
),
s: 1:2-1:4 => S::X {
a: 1:2-1:3 => A::A(
1:2-1:3,
),
s: 1:3-1:3 => S::Z(
1:3-1:3,
),
d: 1:3-1:4,
},
}",
// FIXME(eddyb) get replace quotes with backticks and pretify the `expected` list.
S("aax") => r... | Rust | 0 |
)
self.dec = GeneratorNSF(
inter_channels,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
gin_channels=gin_channels,
is_ha... | Python | 1 |
um_rectangles": target,
"difficulty": {
"max_rectangles": self.config.max_rectangles,
},
},
}
def score_answer(self, answer: Optional[str], entry: dict[str, Any]) -> float:
"""Determine if the solution provided solves the RectangleCoun... | Python | 1 |
essing.Pool(num_cpus) as pool:
gen = pool.imap_unordered(play_pentobi_wrapper, arg_generator(num_games))
while True:
try:
result = next(gen)
results.append(result)
if len(results) % 100 == 0:
print(f"Games played: {len(resul... | Python | 1 |
import json
import pytest
from tornado.httpclient import HTTPRequest
from hmt.serve.admin import make_admin_app
from hmt.serve.mock.scope import Scope
scope = Scope()
@pytest.fixture
def app(mock_data_store, rest_middleware_manager):
return make_admin_app(scope, mock_data_store, rest_middleware_manager)
@pyt... | Python | 1 |
event = Event::TestLiquidationPools(crate::Event::DeviationThresholdChanged(DOT, Rate::zero()));
assert!(System::events().iter().any(|record| record.event == expected_event));
// Can be set to 1.0
assert_ok!(TestLiquidationPools::set_deviation_threshold(
admin(),
DOT,
1_000_000_000_000_000_000u128
));... | Rust | 0 |
import cv2 as cv
import numpy as np
# vid = cv.VideoCapture(0)
# ret, src = vid.read()
src = cv.imread('Photos/frcNote.jpeg')
cv.imshow('frame', src)
blur = cv.GaussianBlur(src, (13,13), 0)
cv.imshow("blur", blur)
hsv = cv.cvtColor(src, cv.COLOR_BGR2HSV)
# mask = cv.inRange(hsv, (0, 150, 140), (12, 255, 255)) old ... | Python | 1 |
數注入
malicious_callbacks = [
"alert('XSS')",
"eval('alert(1)')",
"document.write('<script>alert(1)</script>')",
"window.location='http://evil.com'",
"function(){alert('XSS')}",
"a();alert('XSS');//",
]
for callback in malic... | Python | 1 |
l([e['title'] for e in kdb.groups], ['Internet', 'eMail'])
self.assertEqual(len(kdb.entries), 1)
verify_entry = kdb.entries[0].copy()
verify_entry.update({
'username': 'asdf',
'password': 'asdf',
'url': 'asdf',
'title': ... | Python | 1 |
} else {
0
}) as usize;
let (bottom, top) = (self.video[address], self.video[address + 1]);
for x in (0..8).filter(|&x| {
sprite_x.wrapping_add(x) < SCREEN_SIZE.0 as u16 as i16
&& sprite_x.wrapping_add(x) >= 0
})... | Rust | 0 |
- rhs,
quadratic_part: self.quadratic_part,
quadratic_power: self.quadratic_power,
}
}
#[opimps::impl_ops(Sub)]
#[inline]
fn sub(self: RationalQuadratic, rhs: Rational64) -> RationalQuadratic {
RationalQuadratic {
rational_part: self.rational_part - rhs,
quadratic_part: self.qu... | Rust | 0 |
_base_ = [
'../_base_/models/hv_pointpillars_fpn_nus.py',
'../_base_/datasets/nus-3d.py', '../_base_/schedules/schedule_2x.py',
'../_base_/default_runtime.py'
]
model = dict(
pts_bbox_head=dict(
_delete_=True,
type='FreeAnchor3DHead',
num_classes=10,
in_channels=256,
... | Python | 1 |
inite_string_to_hex));
line.sublines.push(Line::new("ff", "break"));
line
}
fn array_to_hex(
encoding: Option<Encoding>,
array: &[DataItem],
bitwidth: Option<IntegerWidth>,
) -> Line {
let mut line = length_to_hex(Some(array.len()), bitwidth, 4, "array");
line.sublines
.extend(arr... | Rust | 0 |
from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.vectorstores import TencentVectorDB
from langchain_community.vectorstores.tencentvectordb import (
ConnectionParams,
IndexParams,
)
# Create a way to dynamically loo... | Python | 1 |
# Generated by Django 4.2.5 on 2023-10-02 08:02
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_m... | Python | 1 |
heck(cmd);
if !output.status.success() {
println!("{}", String::from_utf8(output.stderr.clone()).unwrap());
}
assert!(output.status.success());
output
}
/// executes the given command, does not check exit status
fn exec_cmd_nocheck(mut cmd: Command) -> Output {
info!("executing: {:?}", cmd)... | Rust | 0 |
tantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ... | Rust | 0 |
class OneTimeKeysManager(object):
"""Handles one-time keys accounting for an OlmDevice."""
def __init__(self, target_keys_number, signed_keys_proportion, keys_threshold):
self.target_counts = {
'signed_curve25519': int(round(signed_keys_proportion * target_keys_number)),
'curve2... | Python | 1 |
model.__class__.__name__, "\n\t".join(error_msgs)
)
)
# Set model in evaluation mode to deactivate DropOut modules by default
model.eval()
if output_loading_info:
loading_info = {
"missing_keys": missing_keys,
"unexpected_keys": unexpected_keys,
"error_msgs": er... | Python | 1 |
#validator for EMTGv9 journeyoptions/missionoptions entries
#Jacob Englander 1/10/2019
def validate(option):
if 'name' not in option:
raise 'missing name field'
elif option['name'] == '':
raise 'empty name field'
if 'dataType' not in option:
raise 'missing dataType in option "' + ... | Python | 1 |
"""
Provide python-space access to the functions exposed in numpy/__init__.pxd
for testing.
"""
import numpy as np
from distutils.core import setup
from Cython.Build import cythonize
from setuptools.extension import Extension
import os
macros = [("NPY_NO_DEPRECATED_API", 0)]
checks = Extension(
"checks",
sou... | Python | 1 |
_parts[3]),
"add" => failed_add(),
"list" => company.list_department(&command_parts.get(1).unwrap_or(&String::from("all"))),
"_debug" => println!("{:#?}", company.employees),
"_demo" => company._demo(),
"quit" | "exit" => exit(0),
_ => print_help()
}
}
fn print_help(... | Rust | 0 |
import os
import pandas as pd
# Caminho da pasta onde estão os CSVs
pasta_produtos = "C:/Users/Samsung/Desktop/Jobs/Base - Analise/Base_Produtos"
pasta_pedidos = "C:/Users/Samsung/Desktop/Jobs/Base - Analise/Base_Pedidos"
pasta_salvar = "C:/Users/Samsung/Desktop/Jobs/Base - Analise/Base_Python"
# Padrões de agrupamen... | Python | 1 |
from .builder import modeling_funcs_builder
# from IPython.display import display, Image, Audio
# import cv2 # We're using OpenCV to read video, to install !pip install opencv-python
import base64
import time
from openai import OpenAI
import os
import base64
import io
# from dataloader import build_data
class ChatGP... | Python | 1 |
import cv2
import sys
if __name__ == '__main__' :
# Set up tracker.
# Instead of MIL, you can also use
tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'MOSSE','CSRT']
tracker_type = tracker_types[5]
if tracker_type == 'BOOSTING':
tracker = cv2.TrackerBoosting_create()
... | Python | 1 |
ettings image shape as 3 x 1024 x 1024
model_save_path = join("./work_dir", 'SAM-ViT-B')
os.makedirs(model_save_path, exist_ok=True)
print(f"LVM-Med (encoder) + tFine-tuned SAM in {cfg.base.dataset_name} with {cfg.train.optimizer}, LR = {cfg.train.learning_rate}")
"""
Load SAM with its original ch... | Python | 1 |
rn_tensor = False
if torch.is_tensor(lr_image):
# or Tensor, [1, 3, H, W], RGB float32
lr_image = (lr_image.detach().permute(0,2,3,1)[0].cpu().numpy() * 255).astype(np.uint8)
return_tensor = True
lr_image = pad_reflect(lr_image, pad_size)
patches, p_... | Python | 1 |
If input is a file, the output path is optional.\n\
If input is a directory, the output path is required",
"FILE",
);
opts.optopt(
"o",
"opath",
"Output path\n
If no output path is provided, it will default to the input path\
... | Rust | 0 |
"text_coverage": 0 # Percentage of image covered by text
}
if detections:
total_confidence = 0
text_area = 0
image_area = image.shape[0] * image.shape[1]
for text, bbox, confidence in detections:
x1, y1, x2, y2 = bbox
area = (x2 - x1) * (y2 ... | Python | 1 |
-> catchain::RawBuffer {
let members = val_set.list().iter().map(|descr| {
let node_id = descr.compute_node_id_short();
let adnl_id = descr.adnl_addr.clone().unwrap_or(node_id.clone());
ton_api::ton::engine::validator::validator::groupmember::GroupMember {
public_key_hash: ton_ap... | Rust | 0 |
from ctypes import c_double, c_int, c_uint, POINTER
from django.contrib.gis.geos.libgeos import lgeos, GEOM_PTR, CS_PTR
from django.contrib.gis.geos.prototypes.errcheck import last_arg_byref, GEOSException
## Error-checking routines specific to coordinate sequences. ##
def check_cs_ptr(result, func, cargs):
"Error... | Python | 1 |
/
/// # Arguments
/// * `log_level`: the log level that should be used.
/// If `None`, the `DEFAULT_LOG_LEVEL` will be used.
/// * `serial_ports`: an iterator over the serial ports that the system logger
/// will write log messages to.
/// Typically this is just a single port, e.g., `&[COM1_BASE_PORT]`.
///
/... | Rust | 0 |
{
let ident = input.parse::<syn::Ident>()?;
match ident.to_string().as_str() {
"ignore" | "skip" => out
.ignore
.replace(SpanContainer::new(ident.span(), None, ident.clone()))
.none_or_else(|_| err::dup_arg(&ident))?,
... | Rust | 0 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Load the CSV
df = pd.read_csv('Data for Roast Comparison.csv')
# Extract X-axis
x = np.arange(1, 51)
# Helper to extract row values
def extract_row(name):
return df[df['Bean Data Type'] == name].iloc[0, 1:].astype(float).values
# Dark Roas... | Python | 1 |
min_end, _ = torch.cat([seg1_e, seg2_e], dim=1).min(1) # batch
max_end, _ = torch.cat([seg1_e, seg2_e], dim=1).max(1)
min_beg, _ = torch.cat([seg1_s, seg2_s], dim=1).min(1)
max_beg, _ = torch.cat([seg1_s, seg2_s], dim=1).max(1)
intersection = min_end - max_beg
intersection... | Python | 1 |
Dead, 3) => Cell::Alive,
// All other cells remain in the same state.
(otherwise, _) => otherwise,
};
next[idx] = next_cell;
}
}
self.cells = next;
}
/// Render the universe as a string.
///
/// To enable this behavior, set the `RENDER_OPTIONS`
/// environmen... | Rust | 0 |
PictureStems = DWRITE_PANOSE_DECORATIVE_CLASS_PICTURE_STEMS,
Ornamented = DWRITE_PANOSE_DECORATIVE_CLASS_ORNAMENTED,
TextAndBackground = DWRITE_PANOSE_DECORATIVE_CLASS_TEXT_AND_BACKGROUND,
Collage = DWRITE_PANOSE_DECORATIVE_CLASS_COLLAGE,
Montage = DWRITE_PANOSE_DECORATIVE_CLASS_MONTAGE,
}
#[derive(C... | Rust | 0 |
shMap<ItemId, AnyItem> = HashMap::new();
let characters = HashMap::new();
let mut rules = RuleBook::new();
rules.load_rules();
World {
characters,
items,
rules,
}
}
pub fn spawn_armor(&mut self, f: ArmorSpawner) -> Option<ItemId> {
... | Rust | 0 |
")]
LastName,
// Custom casing if needed
#[iden(rename = "EMail")]
// the tuple value will be ignored
Email(String),
// Custom method
#[iden(method = "custom_to_string")]
Custom(String),
}
impl Custom {
pub fn custom_to_string(&self) -> &str {
match self {
Self::... | Rust | 0 |
ession.
//
// ```
// enum Action { Move { distance: u32 }, Stop }
//
// fn handle(action: Action) {
// <|>if let Action::Move { distance } = action {
// foo(distance)
// } else {
// bar()
// }
// }
// ```
// ->
// ```
// enum Action { Move { distance: u32 }, Stop }
//
// fn handle(action: Ac... | Rust | 0 |
"""Scan text for time and show links that will pop up a timer if the
user clicks on any time in the TextView."""
import re
from typing import Optional, Union
from gi.repository import GObject, Gtk
from gourmand import timer
from gourmand.convert import NUMBER_FINDER_REGEXP, RANGE_REGEXP, Converter
from gourmand.gtk_... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.