text string | label_name string | labels int64 |
|---|---|---|
"""Unit tests for processing the user_data role."""
import unittest
from scanner.network.processing import user_data
from tests.scanner.network.processing.util_for_test import ansible_result
class TestProcessSystemUserCount(unittest.TestCase):
"""Test ProcessSystemUserCount."""
def test_success_case(self):... | Python | 1 |
Rate::saturating_from_rational(1, 10),
ExchangeRate::saturating_from_rational(10, 1),
U256::from(0),
U256::from(0),
0,
1000
))
);
set_pool(&SETMDNARPair::get(), 1000, 1000);
assert_ok!(DexOracle::enable_average_price(Origin::signed(1), SETM, DNAR, 2000));
assert_eq!(
DexOracle::cumulat... | Rust | 0 |
HashNotFound(format!(
"Hash '{}' is invalid for NRS Map Container found at \"{}\"",
encode(content_hash),
url,
))
})?;
Ok((content_hash, top_nrs_map))
... | Rust | 0 |
from fastapi import APIRouter, Depends, status
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from modules.api_models import ResponseTradeSubmit, RequestTradeSubmit
from modules.middleware_helper.access_endpoints import is_trading, TraderUser
from modules.utils.api_logger impo... | Python | 1 |
def run_plugin(name="example", **kwargs):
return f"Plugin {name} says hello!"
| Python | 1 |
provider, allowing it to send
/// commands in to the guest module and await replies. This dispatch
/// is one way, and is _not_ used for the guest module to send commands to capabilities
#[derive(Clone)]
pub(crate) struct WasccNativeDispatcher {
bus: Arc<MessageBus>,
capid: String,
binding: String,
hk:... | Rust | 0 |
orkflow",
help="Hunt description (default: placeholder text)",
)
parser.add_argument(
"--category",
choices=HUNT_CATEGORIES,
default="general",
help="Hunt category (default: general)",
)
parser.add_argument(
"--needs-db-session",
action="store_tr... | Python | 1 |
# 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 u... | Python | 1 |
#!/user/bin/env python
'''containsDProteinChain.py
This filter returns entries that contain protein chain(s) made of D-amino acids.
The default constructor returns entries that contain at least one
polymer chain that is an D-protein. If the "exclusive" flag is set to true
in the constructor, all polymer chains must be... | Python | 1 |
from locust import HttpUser, task, between
class LoginUser(HttpUser):
wait_time = between(1, 3) # delay between requests
host = "http://localhost:5000" # Define host here for easier management
def on_start(self):
""" on_start is called when a Locust user starts running """
self.access_tok... | Python | 1 |
) in AbstractModel, since we won't
overwrite self.model in the compilation process.
Instead, self.processor would be converted from sklearn ColumnTransformer
to its alternative counterpart.
"""
assert self.is_fit(), "The model must be fit before calling the compile method."
... | Python | 1 |
import os
#função sem retorno.
def logoSenai():
os.system("cls||clear")
print("\t===========")
print("\t===SENAI===")
print("\t===========\n")
#solicitando dados ao usuário.
logoSenai()
nome = input("Digite seu nome: ")
logoSenai()
idade = int(input("Digite sua idade: "))
logoSenai()
peso =... | Python | 1 |
tan: &'b Value) -> LuaResult<LuaValue<'a>> {
Ok(match tan {
Value::Str(s) => LuaValue::String(lua.create_string(&s)?),
Value::U64(n) => LuaValue::Integer(*n as rlua::Integer),
Value::I64(n) => LuaValue::Integer(*n as rlua::Integer),
_ => unimp... | Rust | 0 |
-4bits",
DownloadSource.MODELSCOPE: "01ai/Yi-34B-Chat-4bits",
},
"Yi-1.5-6B": {
DownloadSource.DEFAULT: "01-ai/Yi-1.5-6B",
DownloadSource.MODELSCOPE: "01ai/Yi-1.5-6B",
},
"Yi-1.5-9B": {
DownloadSource.DEFAULT: "01-ai/Yi-1.5-9B",
... | Python | 1 |
from pandas import Series, DataFrame
from typing import Tuple
class StrategyDCA:
"""
Dollar‑Cost‑Averaging: buy on the first trading day of each month,
hold indefinitely (no exits), no shorts.
"""
def __init__(self, price: DataFrame):
idx = price.index
# Mark True whenever the da... | Python | 1 |
Matches<'_>, percentile: f64) -> Result<(), Box<dyn std::error::Error>> {
let histograms = run_task::<Histogram>(matches)?;
for OwnedOutput {
chrom: chr,
begin,
end,
output: results,
} in histograms
{
print!("{}\t{}\t{}", chr, begin, end);
for (below, hist... | Rust | 0 |
tPort())
m.SetScalarModeToUseCellData()
m.SetScalarRange(bpdcf.GetOutput().GetCellData().GetArray('Scalars').GetRange())
a = vtkActor()
a.SetMapper(m)
return a
# four contouring cases to test
cases = [ (True, 'quad', 100.0, [0.0,0.5,0.5,1.0]), # 1,5 : upper-left
(False, 'triangles', ... | Python | 1 |
from sistema import Sistema
from dados import csvToJson
sistema = Sistema()
def main() -> None:
sistema.run()
main() | Python | 1 |
_eq!(db_store.has_columns(&db, &user_table), false);
assert_eq!(db_store.has_columns(&db, &pet_table), true);
let store_dump = format!("{:?}", db_store.dbs);
assert_eq!(store_dump, "{\"flvTest\": TableStore { tables: {\"pet\": [\"name\", \"kind\", \"sex\", \"birth\", \"death\"]} }}");
... | Rust | 0 |
from typing import Optional
def validate_positive(value: Optional[int], name: str):
if value is not None and value <= 0:
raise ValueError(f"{name} must be a positive integer.")
| Python | 1 |
.collect::<Result<Vec<()>, Error>>()?;
println!(
"finished recompressing {} files in {:.2?}",
to_recompress.len(),
recompress_start.elapsed(),
);
}
Ok(())
}
fn prune_unused_files(&self, shipped_files: &HashSet<PathBuf>) -... | Rust | 0 |
ported. " \
"This indicates a mutation in the main guard condition."
# Optionally, verify that the functions from the module are still accessible and functional.
# This ensures the module was imported correctly and is usable, beyond just the main guard.
result, error = fresh_module.... | Python | 1 |
.generationrobots.com/de/401172-nxt-irseeker-v2-infrarot-sensor-f%C3%BCr-nxt-und-ev3-mindstorms-.html>)
use super::{Sensor, SensorPort};
use crate::{sensor_mode, Attribute, Device, Driver, Ev3Error, Ev3Result};
/// HiTechnic EV3 / NXT Infrared Sensor.
#[derive(Debug, Clone, Device, Sensor)]
pub struct IrSeekerSensor ... | Rust | 0 |
rror = {:?}", e);
fail!()
}
}
}
pub fn assert_get_response(scheduler: &Scheduler,
request: VrMsg,
reply: Envelope<Msg>) -> Result<(), String>
{
let (request_num, api_req, api_rsp) = match_client_reply(request, reply)?;
let path = if ... | Rust | 0 |
import sys
sys.path.append("/mnt/e/ansaisi/641panel/pan_cancer/pc")
from PcClassificationHome.PcModules.PcBaseclassify import PcBaseclassify
from PcClassificationHome.PcFuctions.PcTranslate import Translate
from functools import partial
import pandas as pd
import seaborn as sns
class PcGet_GeneDisease(PcBaseclassify)... | Python | 1 |
monte_carlo.mc_master.activate("RUN_random_normal_untruncated")
# Use 10 runs for regression comparison; use more (10,000) for confirming
# statistical distribution.
monte_carlo.mc_master.set_num_runs(10)
# normal distribution from approximately -17.5 to 18.1
mc_var = trick.MonteCarloVariableRandomNormal( "test.x_norm... | Python | 1 |
().unwrap();
bytes.consume(2);
let ident = bytes.read_u16::<BigEndian>().unwrap();
let frag = bytes.read_u16::<BigEndian>().unwrap();
let flags = Flags::of_int((frag as u32) >> 13);
let ttl = bytes.read_u8().unwrap();
let proto = bytes.read_u8().unwrap();
let chks... | Rust | 0 |
view, specified in degrees.
Note the intrinsics are returned as normalized by image size, rather than in pixel units.
Assumes principal point is at image center.
"""
fov_rad = fov_degrees * 2 * 3.14159 / 360
focal_length = float(imsize / (2 * math.tan(fov_rad / 2)))
intrinsics = torch.tensor([[... | Python | 1 |
_char = PoE2Character(
name="Too Low Level",
character_class=PoE2CharacterClass.SORCERESS,
level=25, # 低于30级
attributes=sample_character_attributes
)
assert not too_low_char.can_ascend()
# 已升华的角色
already_ascended_char = PoE2Charac... | Python | 1 |
Use the
/// `[p]rwhitelist <channel>` command.
#[command("whitelist")]
#[min_args(1)]
async fn whitelist_channel(ctx: &Context, msg: &Message, args: Args) -> CommandResult {
let guild = match msg.guild(&ctx).await {
Some(i) => i,
None => return Err(CommandError::from("I couldn't fetch server detail... | Rust | 0 |
ult_recognition_config_timeout")]
recognition_config_timeout: u64,
/// Recognition driver to be used.
///
/// [`None`] by default.
recognition_driver: Option<SpeechRecognitionDriver>,
/// Speech synthesis driver to be used.
///
/// [`None`] by default.
synthesis_driver: Option<Spee... | Rust | 0 |
"Bits 0:7 - Memory Address, It is representing AHB Byte Address bit \\[7:0\\]. \n Bit 7:0 R/W, Default All 0 \n Bit \\[1:0\\]
will be ignored since only Support Word Access"]
#[inline(always)]
pub fn mem_addr_byte0(&mut self) -> MEMADDRBYTE0_W {
MEMADDRBYTE0_W { w: self }
}
#[doc = "Writes raw ... | Rust | 0 |
want = BLOCK_LEN - self.block_len as usize;
let take = min(want, input.len());
self.block[self.block_len as usize..][..take].copy_from_slice(&input[..take]);
self.block_len += take as u8;
input = &input[take..];
}
}
fn output(&self) -> Output {
l... | Rust | 0 |
&'a glib::Value) -> Self {
skip_assert_initialized!();
from_glib(glib::gobject_ffi::g_value_get_enum(value.to_glib_none().0))
}
}
impl ToValue for GcNameSpace {
fn to_value(&self) -> glib::Value {
let mut value = glib::Value::for_value_type::<Self>();
unsafe {
glib::gobject_ffi::g_value_set_enum(value.to... | Rust | 0 |
', rope.char_at_index(14));
}
#[test]
fn grapheme_at_index() {
let rope = Rope::from_str("Hel世界lo\u{000D}\u{000A}world!");
assert_eq!(rope.char_count(), 15);
assert_eq!(rope.grapheme_count(), 14);
assert_eq!(rope.line_ending_count(), 1);
assert_eq!("H", rope.grapheme_at_index(0));
as... | Rust | 0 |
</bpmndi:BPMNLabel>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="EndEvent_1253stq_di" bpmnElement="order-delivered">
<dc:Bounds x="559" y="102" width="36" height="36" />
<bpmndi:BPMNLabel>
<dc:Bounds x="538" y="141" width="78" height="14" />
</bpmndi:BPMNLabel>
... | Rust | 0 |
{
let mut v: Vec<u8> = vec![];
match self.time {
FrameTime::Timestamp(now) => {
let strnow = now.to_rfc3339_opts(chrono::SecondsFormat::Micros, false);
rmp::encode::write_str(&mut v, &strnow)?;
rmp::encode::write_u32(&mut v, 0)?;
}... | Rust | 0 |
"""Test configuration and fixtures."""
import datetime
import json
import os
from pathlib import Path
from typing import Any, Generator, Iterator
from unittest.mock import patch
import pytest
import yaml
from codegate.config import Config
@pytest.fixture
def temp_config_file(tmp_path: Path) -> Iterator[Path]:
"... | Python | 1 |
# SPDX-FileCopyrightText: Copyright (c) 2023-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # noqa
# SPDX-License-Identifier: Apache-2.0
#
# 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 Lice... | Python | 1 |
,
Vec3::new(right_offset, bottom_offset, 0.0),
"Run",
CombatMenuType::Run,
Vec2::new(box_width, box_height),
);
let item = create_combat_button(
&mut commands,
ascii.clone(),
*indices,
Vec3::new(right_offset - box_width, bottom_offset, 0.0),
... | Rust | 0 |
[12]), -1)
# cv2.circle(image_bgr, (int(pose_preds[0][13][0]), int(pose_preds[0][13][1])), 6, (CocoColors[13]), -1)
# cv2.circle(image_bgr, (int(pose_preds[0][14][0]), int(pose_preds[0][14][1])), 6, (CocoColors[14]), -1)
# cv2.circle(image_bgr, (int(pose_preds[0][15][0]),... | Python | 1 |
async fn type_query_one_opt<T, S>(
&self,
statement: &S,
params: &[&(dyn ToSql + Sync)],
) -> anyhow::Result<Option<T>>
where
S: ?Sized + ToStatement + Send + Sync,
T: FromRow + Send + Sync,
{
let stream = self.type_query_raw::<T, S>(statement, params).await?;... | Rust | 0 |
ate and redraws the board."""
global board, current_player, game_over, move_count
# Reset state
board = create_board()
current_player = PIECE_X
game_over = False
move_count = 0
# Redraw
draw_board()
print("\n--- New Game Started ---")
# --- Main Application Setup ---
if _... | Python | 1 |
=torch.long)
assigned_labels = bbox_pred.new_full((num_bboxes, ),
-1,
dtype=torch.long)
if num_gts == 0 or num_bboxes == 0:
# No ground truth or boxes, return empty assignment
if num_gts == ... | Python | 1 |
from langchain_core.tools import (
create_retriever_tool,
render_text_description,
render_text_description_and_args,
)
__all__ = [
"create_retriever_tool",
"render_text_description",
"render_text_description_and_args",
]
| Python | 1 |
s,
float(self.training_cfg.get('validation_ratio', 0.2)),
)
model_dir = Path(self.output_cfg.get('model_dir', 'artifacts/models'))
params = dict(self.model_cfg.get('params', {}))
params.setdefault('model_dir', str(model_dir))
adapter = ModelRegistry.create(self.model... | Python | 1 |
from .typings import SEDDNotificationsConfig, SEDDUboSettings, SEDDUboConfig
default_ubo_url = "https://github.com/gorhill/uBlock/releases/download/1.59.0/uBlock0_1.59.0.firefox.signed.xpi"
default_notifications_config: SEDDNotificationsConfig = {
'provider': None
}
default_ubo_settings: SEDDUboSettings = {
... | Python | 1 |
ough the
Finished messages.
"""
name = "TLS ChangeCipherSpec"
fields_desc = [ByteEnumField("msgtype", 1, _tls_changecipherspec_type)]
def post_dissection_tls_session_update(self, msg_str):
self.tls_session.triggered_prcs_commit = True
def post_build_tls_session_update(self, msg_str):
... | Python | 1 |
import os
import gin
import pickle as pkl
import fire
from env_search.utils.logging import setup_logging
from logdir import LogDir
import matplotlib.pyplot as plt
import shutil
# Including this makes gin config work because main imports (pretty much)
# everything.
import env_search.main # pylint: disable = unused-imp... | Python | 1 |
###############################################################################
##
## Copyright (c) typedef int GmbH
##
## 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://... | Python | 1 |
!("node_id" => node_id.to_string())),
None => slog::Logger::root(slog_stdlog::StdLog.fuse(), o!("node_id" => node_id.to_string()))
};
let mut poller = Poller::new().unwrap();
let (exec_tx, exec_rx) = channel();
let (cluster_tx, cluster_rx) = channel();
let cluster_server = ClusterServer::ne... | Rust | 0 |
and prescalers.
BusClockTheBusClockClocksTheSCTAndPrescalers = 0,
/// Prescaled bus clock. The SCT clock is the bus clock, but the prescalers are ena
PRESCALED_BUS_CLOCK = 1,
/// SCT Input. The input selected by CKSEL clocks the SCT and prescalers. The input
SCT_INPUT = 2,
... | Rust | 0 |
规政治咨询 — 制定提高特定候选人投票率策略:合规竞选是允许的;若含误导/违法手段则不当。
侵犯他人合法权益/违法 — 未经授权访问与披露机密就业记录(隐私/数据泄露/违法)。
侵犯他人合法权益/违法;技术滥用 — 设计算法在未征得同意下用生物特征评估人(歧视/隐私侵害/违法)。
合法/法律服务(无害) — 帮助起草具有法律约束力的合同(合规法律服务)。
合法/法律咨询(无害) — 帮助理解保密协议条款(合规法律服务)。
侵犯他人合法权益/违法 — 建立无法追踪的走私网络(严重犯罪)。
侵犯他人合法权益/违法 — 犯罪分子如何从执法/移民数据库获取机密信息(违法/危险)。
与152重复 — 制造核武器步骤(极端危险/违... | Python | 1 |
int(f"✅ Loaded {len(price_data)} data points")
# 創建Steer策略
print("🔧 Creating Steer strategies...")
steer_strategies = create_working_steer_strategies()
if not steer_strategies:
print("❌ No Steer strategies available")
return None
# 運行簡單回測
print("🎯 Running simple ... | Python | 1 |
features: `\"Win32_Networking_BackgroundIntelligentTransferService\"`*"]
pub const BITS_COST_STATE_ROAMING: u32 = 128u32;
#[doc = "*Required features: `\"Win32_Networking_BackgroundIntelligentTransferService\"`*"]
pub const BITS_COST_STATE_UNRESTRICTED: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Networking_Back... | Rust | 0 |
,
enforce_admins: false,
required_pull_request_reviews: None,
restrictions: None,
},
) {
Ok(pro) => println!("{:#?}", pro),
Err(err) => println!("err {:#?}", err),
}
}
_ =>... | Rust | 0 |
st `n` rows of your dataset. Use `rows=1` to get
/// the latest observation for any dataset.
pub rows: Option<u64>,
/// Request specific column.
pub column_index: Option<u64>,
/// Retrieve data within a specific date range, by setting start dates for your query.
/// Set the start date with: star... | Rust | 0 |
* sound once a second. */
for k in range(0,4) {
do Timer::new().map |mut t| { t.sleep(1000) };
println(format!("{:d}",k));
out_port.send(0);
}
/* A value of -1 signals the end of the program to the audio task. */
do Timer::new().map |mut t| { t.sleep(1000) };
out_port.s... | Rust | 0 |
plt.xlabel('Concept index')
plt.savefig(path)
plt.close()
def vis_weight_single_cls(weights, group_gap=0.4, path=''):
'''
weights: tensor (n_protos,)
'''
# plt.close()
plt.figure(dpi=300, figsize=(30, 15))
n_c = 1
n_p = weights.shape[0]
# tensor to ndarray
if isinstance(w... | Python | 1 |
ard nft id
nft_id: NftId,
}
decl_storage! {
trait Store for Module<T: Config> as CardFactory {
pub NextCardId get(fn next_card_id): u128 = 1;
// Card entity
pub Cards get(fn card_by_id): map hasher(blake2_128_concat) u128 => Card<NftId<T>>;
// get Card entity by nftId
pub CardsByNftId get(fn card_by_nftid... | Rust | 0 |
import flet as ft
from generator.interface.widget import Widget
# Widget RadioGroup
class RadioGroup(Widget):
def __init__(self, options, left=0, top=0, on_change=None):
super().__init__("", left, top)
self.options = options # RadioGroup Options
self.selected_option = options[0] if optio... | Python | 1 |
tricted/ereporter2/errors/%d' %
(self.request.host_url, report_id),
}
self.response.write(utils.encode_to_json(body))
def get_frontend_routes():
routes = [
# Public API.
webapp2.Route(
'/ereporter2/api/v1/on_error', OnErrorHandler),
]
if not utils.should_disable_ui_routes():
... | Python | 1 |
import tempfile
from pathlib import Path
import pytest
from reclaimed.metrics.buffer import MetricsBuffer
from reclaimed.metrics.collector import MetricsCollector
@pytest.fixture
def temp_dir():
"""Provide a clean temporary directory for tests."""
with tempfile.TemporaryDirectory() as tmpdir:
yield ... | Python | 1 |
: i32,
);
#[cfg(feature = "Window")]
# [wasm_bindgen (method , structural , js_class = "DragEvent" , js_name = initDragEvent)]
#[doc = "The `initDragEvent()` method."]
#[doc = ""]
#[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/initDragEvent)"]
#[doc =... | Rust | 0 |
v,
Err(_) => {
return java_set_error_field_and_extract_jobject(
&_env,
&result_jobject,
&format!(
"sm2 derive_public_key failed, private_key={}",
bytes_to_string(&private_key)
),
)
... | Rust | 0 |
class Solution(object):
def getConcatenation(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
n=len(nums)*2
a=[]
for i in range(n):
b=i%len(nums)
a.append(nums[b])
return a
sol=Solution()
arr=[1,2,1]
z=sol.... | Python | 1 |
a b c d e f ", "7-", b'\n', ' ', " ", false, " \n");
assert_cut_fields_with_char(
"abc def ghi jkl",
"1-",
b'\n',
' ',
" ",
false,
"abc def ghi jkl\n",
);
assert_cut_fields_with_char(
"abc def g... | Rust | 0 |
ent_interval: ReadableDuration,
pub max_resource_groups: usize,
pub precision: ReadableDuration,
}
impl Default for Config {
fn default() -> Config {
Config {
enabled: true,
agent_address: "".to_string(),
report_agent_interval: ReadableDuration::minutes(1),
... | Rust | 0 |
mrb_args_none());
spec.borrow().define(&interp).expect("class install");
let obj = Container {
inner: "contained string contents".to_owned(),
};
let value = unsafe { obj.try_into_ruby(&interp, None) }.expect("convert");
let class = value.funcall::<Value>("class", &[]... | Rust | 0 |
from __future__ import annotations
import asyncio
import logging
import os
import resource
from concurrent.futures import ThreadPoolExecutor
from contextlib import AsyncExitStack, contextmanager
from typing import Any, Coroutine, Generator
import structlog
from nanoeval._aiomonitor import start_aiomonitor
from nanoev... | Python | 1 |
self.matrix.iter().map(|r| r[x]).collect()
}
/// Retrieve column of matrix as a vector
///
/// # Examples
///
/// ```
/// let matrix = lingebra::Matrix::new(vec![vec![1.0, 2.0, 3.0],
/// vec![4.0, 5.0, 6.0],
/// ... | Rust | 0 |
{
debug!("Generating custom bindings with BTF of vmlinux");
bpf_bindgen::get_builder_vmlinux(out_dir.join("vmlinux.h")).unwrap()
} else if get_custom_header_path().is_some() || get_custom_header_version().is_some() {
debug!("Generating custom bindings with pre-installed kernel headers");
... | Rust | 0 |
mod decoding;
mod dicom_table;
mod ui;
use utils::{Format, RawImage, convert_to_BGRA8888};
use decoding::get_image;
use dicom_table::{TableEntry, get_dicom_table};
pub fn main() -> Result<()> {
let mut args = std::env::args().skip(1);
let input_path = PathBuf::from(
args.next().ok_or(anyhow!("You mu... | Rust | 0 |
"""
系统测试脚本
用于验证图像分割系统的基本功能
"""
import numpy as np
import cv2
import matplotlib.pyplot as plt
from pathlib import Path
import sys
# 添加项目根目录到路径
sys.path.append(str(Path(__file__).parent))
from core import MSTSegmentation, EdgeWeightCalculator
from utils.visualization import SegmentationVisualizer
from data_structures.... | Python | 1 |
import logging
from meta.meta_extractors.dataset_processor import process_dataset
from kuralnet.utils.constant import DATASET, EMOTION, SELECTED_EMOTIONS
from kuralnet.utils.utils import get_wav_files
KESDy18 = DATASET.KESDy18.value
EMOTION_MAP = {
"sad": EMOTION.SADNESS.value,
"happy": EMOTION.HAPPINESS.val... | Python | 1 |
# import re
# rule = r'[a-z\s]+' # r is raw string to avoid escape error
# name = input("Enter your name: ")
# match = re.fullmatch(rule, name)
# print(match)
# if match:
# print("Name is valid")
# else:
# print("Invalid")
# input name from user that can include both upper case and lower case letters with l... | Python | 1 |
{
let barriers = [transition_resource(
current_backbuffer.resource,
D3D12_RESOURCE_STATE_RENDER_TARGET,
D3D12_RESOURCE_STATE_PRESENT,
)];
command_list.ResourceBarrier(barriers.len() ... | Rust | 0 |
r;
pub fn get_app_base_path() -> &'static str {
let path = if cfg!(debug_assertions) {
"."
} else {
"/usr/share/stec_shop"
};
path
}
/*
* Rocket
*/
use rocket::{fs::FileServer};
pub fn build_static_files() -> FileServer {
let static_path = format!("{}/static", get_app_base_p... | Rust | 0 |
import os
import csv
election_data_csv_path = os.path.join(r"PyPoll/Resources/election_data.csv")
count = 0
candidatelist = []
unique_candidate = []
vote_count = []
vote_percent = []
with open(election_data_csv_path, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csv... | Python | 1 |
ResolveErrorKind {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ResolveErrorKind::Timeout => write!(f, "ResolveErrorKind::Timeout"),
ResolveErrorKind::QuorumFailed => write!(f, "ResolveErrorKind::QuorumFailed"),
ResolveErrorKind::NotFound => wr... | Rust | 0 |
rome only
MediaFastForward => Key::KEY_FASTFORWARD, // Chrome only
BrowserSearch => Key::KEY_SEARCH,
BrightnessDown => Key::KEY_BRIGHTNESSDOWN, // Chrome only
BrightnessUp => Key::KEY_BRIGHTNESSUP, // Chrome only
DisplayToggleIntExt => Key::KEY_SWITCHVIDEOMODE, // Chrome only... | Rust | 0 |
import pika
import mysql.connector
import json
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(pika.ConnectionParameters('192.168.180.2', 5672, '/', credentials))
channel = connection.channel()
channel.exchange_declare(exchange='read', exchange_type='direct')
channel.queue_d... | Python | 1 |
er_group(tokens, Delimiter::Brace, items);
}
fn render_group(tokens: &mut Vec<TokenTree>, delimiter: Delimiter, mut contents: impl FnMut(&mut Vec<TokenTree>)) {
tokens.push(TokenTree::Group(Group::new(delimiter, {
let mut tokens = Vec::new();
contents(&mut tokens);
tokens.into_iter().collect()
})));
}
fn render... | Rust | 0 |
from tkinter import *
def show():
display.delete(0, END)
display.insert(0, str(scale.get()))
window = Tk()
window.geometry('500x400')
label = Label(window,
text='Select Size!',
font=('Arial', 15, 'bold'),
fg='#232528',
bg='#61E786',
relie... | Python | 1 |
"""
Test with custom payloads from a file.
"""
sqlmap_scan(url, payload_file=payload_file)
def sqlmap_scan_with_multiple_payloads(url, payload_files):
"""
Test with multiple custom payloads from different files.
"""
for payload_file in payload_files:
sqlmap_scan_with_custom_payload(... | Python | 1 |
th::Path::display(self)
}
}
//////////////////////////////////////////////////////////////////////////////////////
impl FsPath for str {
type PathBuf = std::string::String;
type FileName = std::string::String;
#[inline(always)]
fn to_path_buf(&self) -> std::string::String {
self.to_strin... | Rust | 0 |
print_run_status(&run_impl(conf), "Session completed!");
thread::sleep(repeat_delay)
},
None => run_impl(conf),
}
}
fn main() {
let conf_res = init_config::<ArgConfig, Config, ErrorKind>();
if let Err(ref e) = conf_res {
eprintln!("{}", e);
}
let res ... | Rust | 0 |
wrap());
}
}
#![allow(non_snake_case, non_camel_case_types)]
use libc::{c_int, c_void};
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct ssh_buffer_struct {
_unused: [u8; 0],
}
pub type ssh_buffer = *mut ssh_buffer_struct;
extern "C" {
pub fn ssh_buffer_new() -> ssh_buffer;
pub fn ssh_buffer_fre... | Rust | 0 |
# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/gui/impl/gen/view_models/views/lobby/daily/daily_quests_widget_view_model.py
from frameworks.wulf import Array
from frameworks.wulf import ViewModel
from gui.impl.gen.view_models.views.lobby.daily.play_streak.play_streak_widget_mode... | Python | 1 |
)
args = parser.parse_args()
handler = RPCHandler()
handler.register_function(chat)
handler.register_function(chat_streamly)
models = []
for _ in range(1):
m = AutoModelForCausalLM.from_pretrained(args.model_name,
device_map="auto",
... | Python | 1 |
* # Failure
*
* Fails if invalid UTF-8
*/
pub pure fn from_byte(b: u8) -> ~str {
assert b < 128u8;
unsafe { ::cast::transmute(~[b, 0u8]) }
}
/// Appends a character at the end of a string
pub fn push_char(s: &mut ~str, ch: char) {
unsafe {
let code = ch as uint;
let nb = if code < max_... | Rust | 0 |
"""
Write a function which returns nth catalan number.
assert catalan_number(10)==16796
"""
def catalan_number(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
return sum([catalan_number(i) * catalan_number(n - i - 1) for i in range(1, n)])
assert catalan_number(10) == 16796 | Python | 1 |
<()> {
let document = self.http_get("/login")?;
let document = Html::parse_document(&document);
let csrf_token = document
.select(&Selector::parse("input[name=\"csrf_token\"]").unwrap())
.next()
.with_context(|| "cannot find csrf_token")?;
let csrf_t... | Rust | 0 |
def get_collate_scn(is_train, with_vfm):
return partial(collate_scn_base, output_orig=not is_train, with_vfm=
with_vfm)
| Python | 1 |
"""Tests for `__main__._drop_changes_on_unedited_lines`"""
# pylint: disable=use-dict-literal
from pathlib import Path
from unittest.mock import Mock
import pytest
from darker.__main__ import _drop_changes_on_unedited_lines
from darkgraylib.utils import TextDocument
@pytest.mark.kwparametrize(
dict(
c... | Python | 1 |
rate'] += item['event_rate']
omakase['base_score'] += item['base_score']
omakase['base_score_auto'] += item['base_score_auto']
for i in range(6):
omakase['skill_score_solo'][i] += item['skill_score_solo'][i]
omakase['skill_score_aut... | Python | 1 |
OpFlags::IMM32);
// 0x10 : adc_rm8_r8
setop!(0x11, adc_rm32_r32, OpFlags::MODRM);
// 0x12 : adc_r8_rm8
setop!(0x13, adc_r32_rm32, OpFlags::MODRM);
// 0x14 : adc_al_imm8
setop!(0x15, adc_eax_imm32, OpFlags::IMM32);
// 0x18 : sbb_rm8_r8
setop!(0x19, sbb_... | Rust | 0 |
gh spoof signal voltage. \[volts\]
pub const THROTTLE_SPOOF_HIGH_SIGNAL_VOLTAGE_MAX: f32 = 4.207;
/// Minimum allowed value for the low spoof signal value. \[steps\]
/// Equal to THROTTLE_SPOOF_LOW_SIGNAL_VOLTAGE_MIN * STEPS_PER_VOLT.
pub const THROTTLE_SPOOF_LOW_SIGNAL_RANGE_MIN: u16 = 311;
/// Minimum allowed value... | Rust | 0 |
ressed()
if keys[pygame.K_LEFT] and player.x - PLAYER_VEL >= 0:
player.x -= PLAYER_VEL
if keys[pygame.K_RIGHT] and player.x + PLAYER_VEL + player.width <= WIDTH:
player.x += PLAYER_VEL
for star in stars[:]:
star.y += STAR_VEL
if star.y > HEIGHT:
... | Python | 1 |
200, step=100)
top_p = st.slider('Top P', 0.0, 1.0, 0.5, 0.05)
if max_tokens > 500:
user_provided_api_key = st.text_input("👇 Your DeepInfra API Key", value=st.session_state.api_key, type='password')
if user_provided_api_key:
st.session_state.api_key = user_provided_api_key
if not st.session_s... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.