text string | label_name string | labels int64 |
|---|---|---|
"ന\u{d3e}ട\u{d4d}യകല",
],
},
#[cfg(feature = "mn")]
crate::Annotation {
lang: "mn",
tts: Some("жүжиг"),
keywords: &["баг", "жүжиг", "театр", "урлаг"],
},
#[cfg(feature = "mr")]
crate::Annotation {
... | Rust | 0 |
raise Exception(f"{parent_name} 以下の to に文字列ではない値が入っています。")
# 複製・ソートの実行
def _duplicate_and_sort(self, context, toml_data, object_list):
self._duplicate_cnt = 0
self._overwrite_cnt = 0
self._duplicate_skip_cnt = 0
self._sort_cnt = 0
#
for object in object_lis... | Python | 1 |
uct RpcGetVoteAccountsConfig {
pub vote_pubkey: Option<String>, // validator vote address, as a base-58 encoded string
#[serde(flatten)]
pub commitment: Option<CommitmentConfig>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RpcLeaderScheduleConfigWrapper {
Sl... | Rust | 0 |
2) NUMBITS(6) [],
/// Battery Precharge to Fast Charge Threshold
BATLOWV OFFSET(1) NUMBITS(1) [
BATLOWV_2_8V = 0,
BATLOWV_3_0V = 1,
],
/// Battery Recharge Threshold (below battery regulation voltage)
VRECHG OFFSET(0) NUMBITS(1) [
VRECHG_100mV ... | Rust | 0 |
from django.urls import path
from . import views as core_views
urlpatterns = [
path(route="", view=core_views.index, name="index"),
path(route="contact-us", view=core_views.contact_us, name="contact-us"),
]
| Python | 1 |
0, enabled.into_glib());
}
}
fn set_spell_checking_enabled(&self, enabled: bool) {
unsafe {
ffi::webkit_web_context_set_spell_checking_enabled(self.as_ref().to_glib_none().0, enabled.into_glib());
}
}
fn set_spell_checking_languages(&self, languages: &[&str]) {
... | Rust | 0 |
_types::Id;
use crate::model::RawAttribute;
// xsd:numFacet
// Complex type information
// Namespace: http://www.w3.org/2001/XMLSchema
// Schema document: datatypes.xsd
//
// Content
// xsd:annotation [0..1]
//
// Attributes
// id [0..1] xsd:ID from type xsd:annotated
// fixed [0..1] xsd:boolean ... | Rust | 0 |
config = if let Some(path_str) = matches.value_of("config") {
let config_file_path = PathBuf::from(path_str.to_string());
let config: Configuration = match read_to_string(config_file_path) {
Ok(str) => match toml::from_str(&str) {
Ok(cfg) => {
... | Rust | 0 |
b14\
b\xa3\xf1\xecs>\x1b\xf8A\xe2\x8f\x8a\xbf\x15uO\
\x18k\xda\x83Y\xb3H\xd6\xba}\xaac\xcb\xb1\xb5\xff\
\x00d\x0e7\xb0\xeezn\xafR\x8b\xc3\x91iq-\
\xad\xad\xbf\x95\x12\x8f\x95S\xf5$\xf5$\xd6\xe4\xbf\xf1\
NEoo/\x95k\xb9\x7f\xd5\xb4\x81y\xc6H\x1d\
3\x5c\xbf\xc4o\x88\xd6\xbe\x03\x8e\xdd\xa5\xb8\x89\xaf.\
\x9dV;U`\xd7\x12n8... | Python | 1 |
)
/// struct containing the first page of maps that fit the search query.
///
/// The default search parameters are:
/// - mode: any
/// - status: has leaderboard (ranked, loved, approved, and qualified)
/// - genre: any
/// - language: any
/// - extra: does neither contain "have video" nor "have storyboard"
/// - nsfw... | Rust | 0 |
-> Settings {
let mut config = Config::default();
let mut config_json = json!({
"provisioning": {
"source": "manual",
"device_connection_string": "HostName=moo.azure-devices.net;DeviceId=boo;SharedAccessKey=boo"
},
"agent": {
... | Rust | 0 |
_| serde_json::from_str::<Value>(self.content.as_str()).ok())
}
fn maybe_as_text(&self) -> Option<String> {
self.extension.as_ref()
.filter(|ext| ext.as_str() == Self::TEXT_EXT)
.map(|_| self.content.to_owned())
}
fn is_json(&self) -> bool {
self.extension.as_re... | Rust | 0 |
as usize;
}
}
let key = keys.last().unwrap(); // handle the last key of all path variants
let transitions = table.get_mut(id).unwrap();
let target = transitions.get_mut(*key).unwrap();
target.1 = Some(ascii as u16);
t... | Rust | 0 |
Coin { lifetime: u8 },
BlockFragment { kind: BlockType, theme: LevelTheme },
}
pub const STAR_ACCEL: f64 = 0.9;
pub const STAR_JUMP: f64 = -20.0;
pub const MUSHROOM_ACCEL: f64 = 0.7;
impl Particle {
pub fn new_coin() -> Self {
const LIFETIME: u8 = 25;
Particle::Coin { lifetime: LIFE... | Rust | 0 |
to close stream and push pending messages in the same
// thread where commands are processed (broker_loop).
// passing Arc<Stream> will prevent dropping stream once we're out of current scope
disconnect_sender
... | Rust | 0 |
ress.to_msg_index()),
/// "2cb59b016d8da9b1d146e212be79282c5a6c9f6df1251e00b950f53beb4b8061".to_string()
/// );
/// # Ok(())
/// # }
/// ```
///
/// ### exchangeable encoding
/// In order to exchange a `TangleAddress` between channel participants, it can be encoded and decoded
/// using [`TangleAddress::to_string... | Rust | 0 |
import unittest
from pyats.topology import loader
from genie.libs.sdk.apis.iosxe.logging.configure import configure_logging_buffer_size
class TestConfigureLoggingBufferSize(unittest.TestCase):
@classmethod
def setUpClass(self):
testbed = """
devices:
c2_core_sf:
connecti... | Python | 1 |
to hide limb constants from cargo doc output.
#[doc(hidden)]
pub const EIGHT_TORSION_INNER_DOC_HIDDEN: [EdwardsPoint; 8] = [
EdwardsPoint {
X: FieldElement2625([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Y: FieldElement2625([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Z: FieldElement2625([1, 0, 0, 0, 0, 0, 0, 0, ... | Rust | 0 |
# Vamos entender a distribuição de idades de pensionistas de uma empresa de previdência.
# Escreva um programa que leia as idades de uma quantidade não informada de clientes e mostre a distribuição em intervalos de [0-25], [26-50], [51-75] e [76-100].
# Encerre a entrada de dados com um número negativo.
idade = int(... | Python | 1 |
f"{_PROVINCES[next(indexes)]}{_CODES[next(indexes)]}"
f"{''.join(_ADS[index] for index in indexes)}"
)
def _get_polygons(image_path: str) -> List[LabeledPolygon]:
attributes: Dict[str, Union[int, str]] = {}
annotations = os.path.splitext(os.path.basename(image_path))[0].split("-", 6)
poi... | Python | 1 |
let result = self.code_struct.code[self.idx];
self.idx += 1;
Some(result)
} else {
None
}
}
}
/// Attempts to parse the given `code_struct` into a `Iterator<Result<Instruction>>`.
///
/// # Errors
/// - `Ok(...)` indicates success.
/// - `Err((Ok(...), ... | Rust | 0 |
demonstration
if __name__ == "__main__":
import asyncio
async def demo_conversation():
"""Demonstrate the basic chat agent with a simple conversation."""
print("=== Basic Chat Agent Demo ===\n")
# Create conversation context
context = ConversationContext(
... | Python | 1 |
+ 1);
*a = *a + 1;
}
fn main() {
let mut s = S { a: 5, b: false };
add1(&mut s.a);
assert(s == S { a: 6, b: false });
}
} => Ok(())
}
test_verify_one_file! {
#[test] test_mut_ref_field_and_update_pass code! {
#[derive(PartialEq, ... | Rust | 0 |
12], [2, 3, 1, 4]),
// Four fingered strings with barre.
case([3, 3, 3, 3], [1, 1, 1, 1]),
case([2, 2, 2, 3], [1, 1, 1, 2]),
case([4, 2, 2, 2], [3, 1, 1, 1]),
case([4, 2, 3, 2], [3, 1, 2, 1]),
case([1, 1, 1, 4], [1, 1, 1, 4]),
case([3, 2, 1, 1], [3, 2, 1, 1]),
... | Rust | 0 |
"""Utilities for normalizing data"""
import numpy as np
def normalize(
x:np.ndarray,
rescale:float=None,
samplewise_center=False,
samplewise_std_normalization=False,
samplewise_normalize_range=None,
dtype:np.dtype=None
) -> np.ndarray:
"""Applies the normalization configuration in-place t... | Python | 1 |
#
# 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 in writing, software
# distributed under the ... | Python | 1 |
9, var_308)?;
object_309.finish();
}
Ok(())
}
pub fn serialize_structure_crate_model_blackout_slate(
object: &mut aws_smithy_json::serialize::JsonObjectWriter,
input: &crate::model::BlackoutSlate,
) -> Result<(), aws_smithy_http::operation::SerializationError> {
if let Some(var_310) = &inpu... | Rust | 0 |
import logging
from sqlalchemy import String, Boolean, BigInteger, select
from sqlalchemy.orm import Mapped, mapped_column
from .database import Base, BaseModelWithTS, DbOperations, get_session
from config import config
logger = logging.getLogger(__name__)
class User(Base, BaseModelWithTS):
__tablename__ = "use... | Python | 1 |
};
if rem.char_at(7) == '5' &&
rem.slice(8, len).chars().all(|c| c == '0') {
n + (n & 1)
} else if rem.char_at(7) >= '5' {
n + 1
} else {
n
... | Rust | 0 |
in Xs]
ls = [loss(y_hat, y) for y_hat, y in zip(y_hats, ys)]
for l in ls:
l.backward()
for idx, param in enumerate(params):
if param.grad_req == "null": continue
kvstore_dist.push(idx, param.grad() / num_samples, priority=-idx)
... | Python | 1 |
# terrascript/vultr/r.py
# Automatically generated by tools/makecode.py ()
import warnings
warnings.warn(
"using the 'legacy layout' is deprecated", DeprecationWarning, stacklevel=2
)
import terrascript
class vultr_bare_metal_server(terrascript.Resource):
pass
class vultr_block_storage(terrascript.Resourc... | Python | 1 |
from krita import DockWidgetFactory, DockWidgetFactoryBase, Krita
from .defaults import (
TAB_CONFIG,
TAB_IMG2IMG,
TAB_INPAINT,
TAB_PREVIEW,
TAB_SDCOMMON,
TAB_TXT2IMG,
TAB_UPSCALE,
)
from .docker import create_docker
from .extension import SDPluginExtension
from .pages import (
ConfigPa... | Python | 1 |
from sqlalchemy import Column, Integer, String, Date, DateTime
from app.database import Base
from datetime import datetime
class Review(Base):
"""
Modelo ORM para representar uma avaliação de cliente no banco de dados.
Attributes:
id (int): Identificador único da avaliação.
cliente (str):... | Python | 1 |
# This file used to measure performance parameters of the torchserve model deployed
# on the Docker container.For single models deployed on the Docker container,
# the system CPU percentage was found to reach 100% afer passing in 4-5 concurrent requests.
# More details can be found out in the Malawi_2020_September.csv ... | Python | 1 |
#[error("unsupported matrix stride {stride} for a {columns}x{rows} matrix with scalar width={width}")]
UnsupportedMatrixStride {
stride: u32,
columns: u8,
rows: u8,
width: u8,
},
#[error("unknown binary operator {0:?}")]
UnknownBinaryOperator(spirv::Op),
#[error("... | Rust | 0 |
f this crate.
#[derive(Debug)]
pub enum Error {
DlOpen(err: dlopen::Error) {
from()
display("dlopen error: {}", err)
source(err)
}
IO(err: io::Error) {
from()
display("io error: {}", err)
source(err)
}
... | Rust | 0 |
'M', 'شخ'),
(0xFD30, 'M', 'شم'),
(0xFD31, 'M', 'سه'),
(0xFD32, 'M', 'شه'),
(0xFD33, 'M', 'طم'),
(0xFD34, 'M', 'سج'),
(0xFD35, 'M', 'سح'),
(0xFD36, 'M', 'سخ'),
(0xFD37, 'M', 'شج'),
(0xFD38, 'M', 'شح'),
(0xFD39, 'M', 'شخ'),
(0xFD3A, 'M', 'طم'),
(0xFD3B, 'M', 'ظم'),
(0x... | Python | 1 |
= "0.0.1"
authors = []
[dependencies.bar]
path = "bar"
"#)
.file("src/main.rs", r#"
extern crate bar;
fn main() { bar::bar(); }
"#)
.file("bar/Cargo.toml", r#"
[package]
name = "bar"
version... | Rust | 0 |
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2024)
#
# 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... | Python | 1 |
Clone)]
enum Slot {
Bool(bool),
I64(i64),
}
impl Display for Slot {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let s = match *self {
Slot::Bool(val) => val.to_string(),
Slot::I64(val) => val.to_string(),
};
write!(f, "{}", s)
}
}
pub struct Progr... | Rust | 0 |
will be included to source code
//! with `include_str!` macro (see `sys/mod.rs`), so that Healer can load them
//! without further manual efforts.
//! One can also skip this process and provide their own build via some extra env vars.
use std::{
env,
fs::{copy, create_dir, read_dir, remove_file, File},
io:... | Rust | 0 |
he `y` register value is added to the address
/// as well.
///
/// * **Assembly Syntax:** `$0000,Y`
/// * If adding `y` changes the page, +1 cycle to the total instruction time.
ABY,
/// Accumulator.
///
/// Similar to `Implicit`, no extra bytes are used and the operation is
/// performed on the `a` ... | Rust | 0 |
class Solution:
# Merge two sorted arrays nums1 and nums2 into nums1 in-place.
def merge(self, nums1: list[int], m: int, nums2: list[int], n: int) -> None:
"""
nums1: The first sorted array with a size of m + n, where the first m elements are valid.
m: The number of valid elements in... | Python | 1 |
import pygame
import sys
# Инициализация Pygame
pygame.init()
# Настройки окна
WIDTH, HEIGHT = 800, 600
FPS = 30
# Цвета
WHITE = (255, 255, 255)
# Инициализация окна
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Sprite Animation")
clock = pygame.time.Clock()
# Класс для анимации
cla... | Python | 1 |
"""
This script generates a large number of samples for five geotechnical feature factors
using Latin Hypercube Sampling (LHS). The sampled values are scaled to their
corresponding ranges and saved into an Excel file for further use.
"""
import pandas as pd
from pyDOE import lhs
# Define the ranges of five feature ... | Python | 1 |
95)
red_team_train = red_team_texts[:split_idx]
red_team_val = red_team_texts[split_idx:]
# Load existing byte data
train_bytes = np.load(train_npy_path)
val_bytes = np.load(val_npy_path)
# Convert and append red team data to training
red_team_tr... | Python | 1 |
json(body);
assert!(!body_result.is_err(), "Unexpected error converting JSON to HTTP body");
let http_body = body_result.unwrap();
assert_eq!(http_body, HttpBody {
data: Vec::from(&b"{\"status\":\"success\",\"data\":{\"messageId\":\"mg9x9vCqYMg9YtKdDwQx\"}}"[..]),
... | Rust | 0 |
ect"]
if result["count"] == 1:
# FIXME: Remove below check when fix from storage layer
# Below check is required as If no streams entry exists in DB storage layer returns response as below:
# {'rows': [{'min_last_object': ''}], 'count': 1}
# BTW it should return i... | Python | 1 |
The address from which the message was sent.
pub address: Option<SocketAddress>,
/// The ancillary data that is associated with this message.
pub ancillary_data: Option<AncillaryData>,
}
impl Message {
/// Creates a a new message with the provided message and ancillary data.
pub fn new(
d... | Rust | 0 |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import os
import numpy as np
from dataset_utils.text_processing import VocabDict
def subset_weights(... | Python | 1 |
pAddr;
use std::time;
use crate::dnstap_pb;
use crate::{MessageType, SocketFamily, SocketProtocol};
/// A DNS message.
///
/// All properties are optional except the message type.
///
/// Although `socket_family` can be explicitly set, it can also be automatically
/// inferred from `query_address` or `response_addres... | Rust | 0 |
_note,
brokerage_note::new_brokerage_note,
brokerage_note::update_brokerage_note,
brokerage_note::delete_brokerage_note
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
use crate::{frame_constants::FrameConstants, util::*};
use macaw::*;... | Rust | 0 |
from fastapi import Body
from configs import logger, log_verbose, LLM_MODELS, HTTPX_DEFAULT_TIMEOUT
from server.utils import (BaseResponse, fschat_controller_address, list_config_llm_models,
get_httpx_client, get_model_worker_config)
from typing import List
def list_running_models(
contr... | Python | 1 |
1_1_1(buffer.as_ptr() as *const _, buffer.len() as usize) }
}
/// Returns a 128-bit CityHash of the given slice of bytes.
///
/// ```
/// # fn main() {
/// use cityhash::cityhash_1_1_1::city_hash_128;
///
/// assert_eq!(city_hash_128(b"sentences"), 0x0C86_49F6_4B31_D024_0DCC_335E_F92D_3406);
/// # }
pub fn city_hash_1... | Rust | 0 |
# def simple_genrator():
# # yield 1
# # yield 2
# # yield 3
# for i in range(10):
# yield i
# gen = simple_genrator()
# for value in gen:
# print(value)
def fibonacchi_genrator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fin_gen = fibonacchi_genra... | Python | 1 |
uct Asset {
#[serde(rename = "url")]
url: String,
#[serde(rename = "id")]
id: i64,
#[serde(rename = "node_id")]
node_id: String,
#[serde(rename = "name")]
name: String,
#[serde(rename = "label")]
label: Option<serde_json::Value>,
#[serde(rename = "uploader")]
uploade... | Rust | 0 |
, 3],
]
);
}
}
use std::env;
mod api;
mod cli;
mod consts;
mod daemon;
mod error;
mod folders;
mod io;
mod state;
mod vm;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
if env::var_os("RUST_LOG").is_none() {
env::set_var("RUST_LOG", "in... | Rust | 0 |
ut a specific node power limit.
# Let's use the node power models to distribute the job power limit.
hook_config = None
if pbs.hook_config_filename is not None:
with open(pbs.hook_config_filename) as f:
hook_config = json.load(f)
vnode_names = [v.name for v in... | Python | 1 |
[doc = "*Required features: `\"Win32_NetworkManagement_WindowsFirewall\"`*"]
pub const NCS_HARDWARE_DISABLED: NETCON_STATUS = 5i32;
#[doc = "*Required features: `\"Win32_NetworkManagement_WindowsFirewall\"`*"]
pub const NCS_HARDWARE_MALFUNCTION: NETCON_STATUS = 6i32;
#[doc = "*Required features: `\"Win32_NetworkManagem... | Rust | 0 |
if play_by_play_table:
pbp_row = play_by_play_table.find(
"span", class_="name", string=player_name
)
if pbp_row:
pbp_row = pbp_row.find_parent("tr")
at_bat_c... | Python | 1 |
from collections import deque
def demo_deque_operations():
print("=== Deque Demonstration ===\n")
# 1. Create an empty deque
dq = deque()
print("1. Empty Deque:", dq)
# 2. Append to right (like normal queue enqueue)
dq.append(10)
dq.append(20)
dq.append(30)
print("2. After app... | Python | 1 |
-load-store.txt") {
return true;
}
if test.ends_with("logging-all-opcodes.txt") {
return true;
}
false
}
fn skip_wabt_compare(test: &Path) -> bool {
// Looks like wabt doesn't implement table.fill yet
if test.ends_with("reference-types/table_fill.wast") {
return true;
... | Rust | 0 |
Token::Ident("define".to_string()),
Token::Ident("nil".to_string()),
Token::Quote,
Token::Lparen,
Token::Rparen,
Token::Rparen,
];
let lex = Lexer::new(source);
for (tok, expected_tok) in lex.zip(expected) {
assert_eq!(
... | Rust | 0 |
s(vals)
}
pub fn execute_call(&mut self, funcidx: &FuncIdx) -> Result {
let (_, frame) = self.current_frame();
let a = frame.module.funcaddrs[funcidx.clone() as usize];
self.execute_invoke(&a)
}
pub fn execute_callindirect(&mut self, funcidx: &FuncIdx) -> Result {
let (... | Rust | 0 |
ll_tags:
tags.add("#(" + tag)
tags -= all_tags
for tag in tags:
model.append([tag])
all_tags.update(tags)
print_d("Done updating tag model for whole library")
class LibraryValueCompletion(Gtk.EntryCompletion):
"""Entry completion for a library value, f... | Python | 1 |
from flask import Flask, request
import telebot
import twilio_integration
import bot_handlers
app = Flask(__name__)
# Inizializza il bot con il token
bot = telebot.TeleBot('YOUR_TELEGRAM_BOT_API_TOKEN')
# Definisci la route per il webhook di Telegram
@app.route('/telegram-webhook', methods=['POST'])
def telegram_web... | Python | 1 |
driver exists for the LIS2DH12, so this provides direct
/// access to the I2C bus it's connected to.
pub LIS2DH12: Twim<nrf52::TWIM1>,
/// nRF52 nRF52 core peripheral: Cache and branch predictor maintenance
/// operations
pub CBP: nrf52::CBP,
/// nRF52 core peripheral: CPUID
pub CPUID: nr... | Rust | 0 |
parser.add_argument('--weight_decay',
default=0.00005, type=float)
parser.add_argument('--epsilon', type=float,
default=1e-8)
parser.add_argument('--batchsize', help='Batch size for training',
default=1, type=int)
parser.add_argume... | Python | 1 |
's command port.
/// More esoteric commands (nearly a full list) are here: <https://wiki.osdev.org/ATA_Command_Matrix>.
#[repr(u8)]
enum AtaCommand {
/// Read sectors using PIO (28-bit LBA)
ReadPio = 0x20,
/// Read sectors using PIO (48-bit LBA)
ReadPioExt = 0x24,
/// Read sectors using DMA (28-bit L... | Rust | 0 |
::Disconnected) => unreachable!(),
}
match self.cap.next() {
Ok(pkt) => {
let now = pkt.header.ts;
let now = now.tv_sec as u64 * 1_000_000_000 + now.tv_usec as u64 * 1_000; // ns since epoch
let data = pkt.data;
self.bytes_recv... | Rust | 0 |
.overlap_graph()
path_groups = []
root_nodes = [i for i, d in G.in_degree() if d == 0]
for root in root_nodes:
if self[root].path.filling == Filling.FILL:
current = [root]
while current:
n = current.pop(0)
fi... | Python | 1 |
_owner_id: AccountId,
pub amount: Balance,
pub fee: Balance,
pub proof: Proof,
}
pub struct WithdrawCallArgs {
pub recipient_id: AccountId,
pub amount: Balance,
}
pub struct TransferCallCallArgs {
pub receiver_id: AccountId,
pub amount: Balance,
pub memo: Option<String>,
pub msg: S... | Rust | 0 |
lf>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
forward_call!(self, poll_shutdown, cx)
}
}
impl Connection for ProxyHttpStream {
fn connected(&self) -> Connected {
let conn = Connected::new();
if self.negociated_http2() {
conn.negotiated_h2()
} else {
... | Rust | 0 |
#[async_trait]
pub trait BasicAuthValidator: Send + Sync {
/// Validate is that username and password is right.
#[must_use = "validate future must be used"]
async fn validate(&self, username: &str, password: &str) -> bool;
}
/// BasicAuthDepotExt
pub trait BasicAuthDepotExt {
/// Get basic auth usernam... | Rust | 0 |
import pytest
from trinity.plugins.builtin.attach.console import console
from pathlib import Path
from trinity.utils.log_messages import (
create_missing_ipc_error_message,
)
def test_console(caplog, jsonrpc_ipc_pipe_path):
# if ipc_path is not found, raise an exception with a useful message
with pytest.... | Python | 1 |
from openai import OpenAI
from requests import get
from bs4 import BeautifulSoup
client = OpenAI()
# openai_key ='API Key from OpenAI'
# client = OpenAI(api_key=openai_key)
def scrape(url):
page = get(url).text
soup = BeautifulSoup(page, 'html.parser')
post = soup.find_all('p')
text =''
for line ... | Python | 1 |
::scopes::ScopeConfig>,
arg_name: StringLenPtr,
check_all_args: c_uint,
) -> Option<&'sc xcfg::XCheckType> {
let res = scope_config.and_then(|sc| match sc.item {
xcfg::scopes::ItemConfig::Function(ref f) => {
let arg_index = xcfg::FieldIndex::Str(String::from(arg_name.as_str()));
... | Rust | 0 |
= prev_x.item() * std_x + mean_x
ori_y = prev_y.item() * std_y + mean_y
# ori_x = prev_x.item()
# ori_y = prev_y.item()
current_generated_shot.append(ori_shot)
current_generated_area.append((ori_x, ori_y))
current_loss['entropy... | Python | 1 |
sionState(outcomes=['retry', 'fail'],
hint='retry',
suggestion='retry'),
transitions={'retry': 'LogReplan' # 441 230 -1 -1 362 223
... | Python | 1 |
from django.utils.translation import gettext as _
from django.utils.translation import pgettext
from rules.contrib.views import PermissionRequiredMixin
from adhocracy4.comments.models import Comment
from adhocracy4.exports import mixins
from adhocracy4.exports import views as a4_export_views
from . import models
cl... | Python | 1 |
nused)] pub fn len(&self) -> usize {
self.n_points as usize
}
/// Abort program on error if the octree is corrupt!
#[allow(unused)] pub fn check_corrupt(&self) {
// self.check_corrupt_node(self.root - 1, self.bcube, 0);
}
/// Print a node and its descendants
fn check_corrupt_node(&self, i: usize, bcube: BCube,... | Rust | 0 |
"""
Run all available algorithm examples.
"""
import os
import subprocess
import sys
from pathlib import Path
def run_all_examples():
"""Run all example scripts."""
# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent / 'src'))
examples_dir = Path(__file__).parent / 'superv... | Python | 1 |
ables(http_protocol: str):
with load_env_var("UVICORN_HTTP", http_protocol):
runner = CliRunner(env=os.environ)
with mock.patch.object(main, "run") as mock_run:
runner.invoke(cli, ["tests.test_cli:App"])
_, kwargs = mock_run.call_args
assert kwargs["http"] == http... | Python | 1 |
eturn data
class GridWorldEnv(gym.Env):
def __init__(self, maze_file, goal_reward, trap_reward, step_reward, exit_reward, bait_reward, bait_step_penalty, max_step, render_mode="human") -> None:
super(GridWorldEnv, self).__init__()
self.render_mode = render_mode
self.grid_world = GridWorld(... | Python | 1 |
2.dnn.blobFromImage(frame, 1 / 255.0, (320, 320), crop=True)
net.setInput(blob)
layerOutputs = net.forward(ln)
boxes = []
confidences = []
for output in layerOutputs:
for detection in output:
scores = detection[5:]
classID = np.argmax... | Python | 1 |
s (actor));
joinable!(users -> roles (user_role));
allow_tables_to_appear_in_same_query!(
comments,
moderation_actions,
pages,
posts,
roles,
routes,
user_actions,
users,
);
<gh_stars>0
mod color;
use image;
use rand::{thread_rng, Rng};
use tokio::sync::mpsc;
const WIDTH: u32 = 1024;
c... | Rust | 0 |
impl_outer_origin, impl_outer_event, assert_ok, assert_err, parameter_types, weights::Weight};
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup}, testing::Header, Perbill,
};
impl_outer_origin! {
pub enum Origin for TestRuntime {}
}
#[derive(Clone, Eq, PartialEq)]
pub struct TestRuntime;
parameter_ty... | Rust | 0 |
code(),
Instruction::LD1SH_z_p_bz_d_x32_unscaled { xs: 1, Zm: 31, Pg: 7, Rn: 31, Zt: 31, })
}
#[test]
fn roundtrip_LDFF1SH_z_p_bz_d_x32_unscaled() {
assert_eq!(Instruction::LDFF1SH_z_p_bz_d_x32_unscaled { xs: 1, Zm: 31, Pg: 7, Rn: 31, Zt: 31, }.encode().decode(),
Instruction::LDFF1... | Rust | 0 |
import numpy as np
a = np.array([1, 100, 10])
print(a)
# [ 1 100 10]
print(np.argmax(a))
# 1
a = np.array([1, 10, 10])
print(a)
# [ 1 10 10]
print(np.argmax(a))
# 1
a_2d = np.array([[20, 50, 30], [60, 40, 10]])
print(a_2d)
# [[20 50 30]
# [60 40 10]]
print(np.argmax(a_2d))
# 3
print(a_2d.flatten())
# [20 50 3... | Python | 1 |
t LEFT_INPUT_MEMORY_BUFFER: *const f32 = 0x0 as *mut f32;
pub static mut RIGHT_INPUT_MEMORY_BUFFER: *const f32 = 0x0 as *mut f32;
#[no_mangle]
fn get_left_audio(offset: i32) -> f32 {
unsafe {
*LEFT_INPUT_MEMORY_BUFFER.offset(offset as isize)
}
}
#[no_mangle]
fn get_right_audio(offset: i32) -> f32 {
... | Rust | 0 |
use prettytable::{Table, Row, Cell};
use clap::Clap;
mod html_document;
mod validator;
#[derive(Clap, Debug)]
#[clap(name = "website polish")]
struct Args {
website_url: String,
keywords: Vec<String>
}
async fn fetch_http(url: &str) -> Result<String, Box<dyn std::error::Error>> {
let html = reqwest::get... | Rust | 0 |
=> "Method Not Allowed",
406, "406", NotAcceptable => "Not Acceptable",
407, "407", ProxyAuthenticationRequired => "Proxy Authentication Required",
408, "408", RequestTimeout => "Request Timeout",
409, "409", Conflict => "Conflict",
410, "410", Gone => "Gone",
411, "411",... | Rust | 0 |
:], np.array(cam['K']), cam['R'], cam['t'], cam['distCoef'])
kpts2d_J24 = np.zeros((24, 3))
kpts2d_J24[:, :2] = pt_J24[:2].T
kpts2d_J24[:, -1] = kpts3d_J24[:, -1]
s_kpts2d = np.zeros_like(kpts2d_J24)
s_kpts2d[..., -1] = kpts2d_J24[..., -1]... | Python | 1 |
ED {
self.change_pal(self.palette_id_requested as usize);
self.palette_id_requested = NO_PALETTE_CHANGE_REQUESTED
}
//Q: Why 160 ?
//A: Because one byte gives two palette indices so
// we only need to move 320/2 per line.
self.sys
.get_mut()... | Rust | 0 |
orations && screen.is_none() || pl_attrs.titlebar_hidden {
// Resizable UnownedWindow without a titlebar or borders
// if decorations is set to false, ignore pl_attrs
NSWindowStyleMask::NSBorderlessWindowMask
| NSWindowStyleMask::NSResizableWindowMask
| NSWindowStyleMask::NSMiniaturiza... | Rust | 0 |
let mut new_header = args
.next()
.expect("Pass a header after the '--header' flag")
.to_string();
if !new_header.contains(':') {
if new_header.contains('=') {
new_header = new_header.... | Rust | 0 |
ysis_results: List[Dict], filename: str = None):
"""Save analysis results to JSON file"""
if filename is None:
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
filename = f'lab_record_analysis_{timestamp}.json'
with open(filename, 'w') as f:
json.... | Python | 1 |
import asyncio
import json
from random import randint
from urllib.parse import urlparse, parse_qs
from fake_useragent import UserAgent
from httpx import AsyncClient
from ._logger import logger
class WechatOfficialAccountFetcher:
def __init__(
self,
cookie: str,
url: str,
... | Python | 1 |
draw_text += _("\n博士的精子与{0}的卵子结合,成功在子宫里着床了\n").format(character_data.name)
draw_text += _("\n{0}获得了[受精]\n").format(character_data.name)
draw_text += "\n※※※※※※※※※\n"
character_data.talent[20] = 1
character_data.pregnancy.fertilization_time = cache.gam... | Python | 1 |
# Importing OpenCV Library for basic image processing functions
import cv2
# Numpy for array related functions
import numpy as np
# Dlib for deep learning based Modules and face landmark detection
import dlib
# face_utils for basic operations of conversion
from imutils import face_utils
# Initializing the camera and t... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.