text string | label_name string | labels int64 |
|---|---|---|
-> String {
let schema = indoc! {
r#"model ModelA {
#id(id, Int, @id)
b_id Int?
b ModelB? @relation(fields: [b_id], references: [id])
c ModelC?
}
model ModelB {
#id(id, Int, @id)
a Mo... | Rust | 0 |
import argparse
import logging
import os
from collections import namedtuple
def get_dir_info(path: str):
FileInfo = namedtuple('FileInfo', 'name extension is_catalog parent_dir')
try:
os.chdir(path)
except FileNotFoundError as ex:
logging.error(ex)
raise FileNotFoundError(ex)
i... | Python | 1 |
"Works!"
//! }
//!
//! my_function(turbonone!()); // Works!
//! my_function(Some("An argument")); // Works!
//!
//! my_box_function(turbonone!(Box)); // Works!
//! my_box_function(turbonone!(Box<()>)); // Works!
//! my_box_function(Some(Box::new("An argument"))); // Works!
//!
//! my_complex_function(turbonone!(Arc<Box... | Rust | 0 |
8, 0.1, 0., 0., 0.1]));
// assert_eq!(score, (0. + 0.1) / 2.);
// }
#[test]
fn calc_offset() {
let offset = MultipleSequenceAlignment::calc_offset(4, 2, 10);
assert_eq!(offset, 2);
assert_eq!(MultipleSequenceAlignment::calc_offset(4, 5, 20), 0);
assert_eq!(MultipleSeq... | Rust | 0 |
import keras
from keras.layers.convolutional import Conv3D, MaxPooling3D
from keras.layers import Dense, Flatten, Dropout
from keras.models import Sequential
from keras.optimizers import Adam
from config import NUM_CLASSES, VIDEO_DIMENSIONS, FRAMES_PER_VIDEO
ADAM_LEARNING_RATE = 1e-5
ADAM_DECAY_RATE = 1e-6
class P... | Python | 1 |
"Checks if the value of the field is `TCC1_MC_1`"]
#[inline(always)]
pub fn is_tcc1_mc_1(&self) -> bool {
*self == TRIGSRC_A::TCC1_MC_1
}
#[doc = "Checks if the value of the field is `TCC1_MC_2`"]
#[inline(always)]
pub fn is_tcc1_mc_2(&self) -> bool {
*self == TRIGSRC_A::TCC1_MC... | Rust | 0 |
es() {
map.push(line.parse()?);
}
Ok(map)
}
fn exec(&self) -> bool {
self.flags.contains('x')
}
}
impl FromStr for MemoryMapEntry {
// TODO: proper error
type Err = io::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut columns = s.spl... | Rust | 0 |
# ----------------------------------------------------------------------------
# SymForce - Copyright 2022, Skydio, Inc.
# This source code is under the Apache 2.0 license found in the LICENSE file.
# ----------------------------------------------------------------------------
from __future__ import annotations
from ... | Python | 1 |
from django.conf import settings
import logging
import sys
from django.apps import AppConfig
import sys
import os
chatbotPath = "/".join(settings.BASE_DIR.split('/')[:-1])
sys.path.append(chatbotPath)
from chatbot import chatbot
logger = logging.getLogger(__name__)
class ChatbotManager(AppConfig):
""" Manage ... | Python | 1 |
#!/usr/bin/env python3
import os
import shutil
import sys
from pathlib import Path
dist_dir = os.getenv("DIST_DIR")
if not dist_dir:
sys.stderr.write("empty DIST_DIR!")
sys.exit(1)
dist_dir_path = Path(dist_dir)
if not dist_dir_path.exists():
sys.stderr.write(f"DIST_DIR does not exist: {dist_dir}")
sys.exit(1)... | Python | 1 |
encies) != 0:
sys.exit(1)
# Order dependencies
sorted_dependency_graph = []
max_iterations = pow(len(dependency_graph),2)
while dependency_graph:
deleted_packages = []
if max_iterations == 0:
# One day be more helpful and find the actual cycle for the user...
... | Python | 1 |
);
while cinfo.output_scanline < cinfo.output_height {
num_scanlines = crate::jpeglib_h::jpeg_read_scanlines(
&mut cinfo,
(*dest_mgr).buffer,
(*dest_mgr).buffer_height,
);
Some(
(*dest_mgr)
... | Rust | 0 |
})
});
}
use std::cell;
use std::mem;
use gc::{GcPtr, Trace, NullTrace};
use crate::{Gc, GcStore};
pub unsafe trait Reroot<'root> {
type Rerooted: ?Sized + 'root;
}
pub unsafe fn reroot<'root, T>(data: GcPtr<T>) -> GcPtr<T::Rerooted> where
T: Reroot<'root> + ?Sized,
T::Rerooted: Trace,
{
let ptr: ... | Rust | 0 |
import numpy as np # Importa a biblioteca NumPy para operações matriciais
from sympy import Matrix # Importa a biblioteca SymPy para trabalhar com álgebra simbólica
# Esta é a matriz usada como chave para criptografar e descriptografar o texto.
# A Cifra de Hill exige que seja uma matriz quadrada (n x n), neste caso... | Python | 1 |
from enum import Enum
from typing import (
Dict,
Tuple,
)
from hummingbot.core.api_throttler.data_types import RateLimit, LinkedLimitWeightPair
class KrakenAPITier(Enum):
"""
Kraken's Private Endpoint Rate Limit Tiers, based on the Account Verification level.
"""
STARTER = "STARTER"
INTERM... | Python | 1 |
use cortex_m::peripheral::NVIC;
use stm32f7xx_hal::device::{self, EXTI, SYSCFG, USART3};
use stm32f7xx_hal::gpio::gpiob::PB;
use stm32f7xx_hal::gpio::gpioc::PC13;
use stm32f7xx_hal::gpio::{gpiob, gpioc, gpiod, Edge, ExtiPin, Floating, Input, Output, PushPull};
use stm32f7xx_hal::interrupt;
use stm32f7xx_hal::rcc::Cloc... | Rust | 0 |
new(&client.credentials.0, &client.credentials.1, &client.ext_uris, client_tr_id.as_str());
client.transact::<_, EppLoginResponse>(&login_request).await?;
Ok(client)
}
/// Executes an EPP Hello call and returns the response as an `EppGreeting`
pub async fn hello(&mut self) -> Result<EppGr... | Rust | 0 |
OP_NO_TLSv1),
// "OP_NO_TLSv1_1" => ctx.new_int(sys::SSL_OP_NO_TLSv1_1),
// "OP_NO_TLSv1_2" => ctx.new_int(sys::SSL_OP_NO_TLSv1_2),
"OP_NO_TLSv1_3" => ctx.new_int(sys::SSL_OP_NO_TLSv1_3),
"OP_CIPHER_SERVER_PREFERENCE" => ctx.new_int(sys::SSL_OP_CIPHER_SERVER_PREFERENCE),
"OP_SING... | Rust | 0 |
subprocess.run([str(RUNNER_PATH), "start"])
else:
print("not installed")
elif c == "4":
if RUNNER_PATH.exists():
subprocess.run([str(RUNNER_PATH), "stop"])
else:
print("not installed")
elif c == "5":
if RUN... | Python | 1 |
ve upon which the entire system is built.
//! All kernel services are accessed through messages sent to capabilities which the kernel
//! recognizes as belonging to kernel objects. Threads can also use this mechanism to send messages
//! between themselves.
//!
//! Endpoints represent authorization to receive or send m... | Rust | 0 |
.0.h) >= self.0.outlen as usize);
let raw_ptr = (&self.0.h[..]).as_ptr() as *const u8;
unsafe { slice::from_raw_parts(raw_ptr, self.0.outlen as usize) }
}
}
impl ::std::fmt::Debug for Blake2bHasher {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
write... | Rust | 0 |
# Generated by fragment (with the help of ariadne-codegen)
# Source: queries/
from typing import Any, List, Optional
from pydantic import Field
from .base_model import BaseModel
class ListLedgerEntries(BaseModel):
ledger: Optional["ListLedgerEntriesLedger"]
class ListLedgerEntriesLedger(BaseModel):
ledge... | Python | 1 |
num = int(input('Digite um numero: '))
if num >= 5:
print(f'O numero digitado {num} é MAIOR que 5.')
else:
ptint(f'O numero {num} é que 5.') | Python | 1 |
CHAR) => State::Opening,
(State::Default, _) => State::Default,
// Closing
(State::Closing, CLOSE_CHAR) => State::Closing,
(State::Closing, COMMENT_CHAR) => {
nesting_count -= 1;
if nesting_count == 0 {
... | Rust | 0 |
inates are halved before clicking
{api_section}
[debug]
# Debug and logging settings
# enabled = false
# folder = "" # Empty = no debug output
# log_file = "debug.log"
# images_subfolder = "images"
# log_rotation = "10 MB"
# log_retention = "7 days"
# log_compression = "gz"
[annotation]
# Visual annotation settings... | Python | 1 |
#!/usr/bin/env python3
# Lab: CSRF vulnerability with no defenses
# Lab-Link: https://portswigger.net/web-security/csrf/lab-no-defenses
# Difficulty: APPRENTICE
from bs4 import BeautifulSoup
import requests
import sys
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
proxies = {'http': ... | Python | 1 |
"""
風險控制系統整合驗證腳本
驗證實時風險控制系統的所有功能是否正常運作,包括:
- 模組導入檢查
- 基本功能驗證
- 整合流程測試
- 向後兼容性檢查
"""
import sys
import traceback
from datetime import datetime
from unittest.mock import Mock
def test_module_imports():
"""測試模組導入"""
print("🔍 檢查模組導入...")
modules_to_test = [
("資金監控基礎", "src.risk.live.fund_monit... | Python | 1 |
tus = super().get_update_status()
# XXX - Currently this reports status matching
# that of the git repo so as to not break existing
# client functionality. In the future it would be
# good to report values that are specifc
status.update({
'detected_type': "zip",
... | Python | 1 |
.as_vector2d()
.add(&(tmp_normvecs[i].mult(0.5).mult(tmp_sign).mult(bound_length)))
.as_point2d();
let tmp_p2 = tmp_coords[i]
.as_vector2d()
.sub(&(tmp_normvecs[i].mult(0.5).mult(tmp_sign).mult(bound_length)))
.as_point2d(... | Rust | 0 |
ath<W, P, Q>(
&self,
mut builder: &mut tar::Builder<W>,
root_dir: P,
path: Q,
) -> Result<(), std::io::Error>
where
W: std::io::Write,
P: AsRef<std::path::Path>,
Q: AsRef<std::path::Path>,
{
let root_dir = root_dir.as_ref();
let path = ... | Rust | 0 |
if i1 == i2 {
continue;
}
if bounds[i1].overlaps(&bounds[i2]) {
slow_collisions.push((&bounds[i1], &bounds[i2]));
}
}
}
assert!(collisions.len() == slow_collisions.len());
}
<reponame>isaacazuelos/kurt
//! An object is the r... | Rust | 0 |
orbits.append(o)
orbits.sort()
return orbits
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
r"""
Let Sage knows that Cartesian products of commutative rings is a
commutative ring.
EXAM... | Python | 1 |
::InUse,
}
}
}
impl From<ReplyError> for crate::common::ReplyError {
fn from(err: ReplyError) -> Self {
let kind: common::ReplyErrorKind = err.clone().kind.into();
let resource: common::ResourceKind = err.clone().resource.into();
crate::common::ReplyError {
kind: kin... | Rust | 0 |
g.speaking_order == "round-robin":
ai = self.ais[self.current_speaker_index]
self.current_speaker_index = (self.current_speaker_index + 1) % len(self.ais)
return ai
else: # random
return random.choice(self.ais)
async def generate_next_message(self) -> Op... | Python | 1 |
");
let rx_dataset = randomx_rs::RandomXDataset::new(rx_flags, &rx_cache, 0).unwrap();
debug!("[worker] dataset created");
let rx_vm =
randomx_rs::RandomXVM::new(rx_flags, Some(&rx_cache), Some(&rx_dataset)).unwrap();
debug!("[worker] randomx vm created");
loop {
... | Rust | 0 |
X_Vfnmadd213pd_xmm_k1z_xmm_xmmm128b64
0x00AC_0002, 0x0320_9409, 0x0002_229F,// EVEX_Vfnmadd213pd_ymm_k1z_ymm_ymmm256b64
0x00AC_0002, 0x0360_D809, 0x0002_32E0,// EVEX_Vfnmadd213pd_zmm_k1z_zmm_zmmm512b64_er
0x00AD_0001, 0x0000_1409, 0x0002_53A2,// VEX_Vfnmadd213ss_xmm_xmm_xmmm32
0x00AD_0001, 0x0000_3409, 0x0002_53A2,... | Rust | 0 |
Base64DecodeError(err: FromBase64Error) {
from()
description(err.description())
display("{}", err)
}
Utf8Error(err: Utf8Error) {
from()
description(err.description())
display("{}", err)
}
SerdeJson(err: serde_json::Error) {
from()
descrip... | Rust | 0 |
! ```shell
//! $ docker run -d -p 9411:9411 openzipkin/zipkin
//! ```
//!
//! Then install a new pipeline with the recommended defaults to start exporting
//! telemetry:
//!
//! ```no_run
//! use opentelemetry::trace::{Tracer, TraceError};
//! use opentelemetry::global;
//!
//! fn main() -> Result<(), TraceError> {
//!... | Rust | 0 |
(); btn_pause.config(text="Resume")
btn_pause = ttk.Button(top, text="Pause", command=_on_pause_toggle); btn_pause.pack(side="right", padx=(6,0))
ttk.Button(top, text="Stop", command=lambda: self.ft_stop.set()).pack(side="right", padx=(6,0))
self.ft_preview = tk.Text(tab_ft, height=14, wrap="... | Python | 1 |
TGeometry(WGS84_PROJECTION, bbox, periods[1])),
# Full third time period.
Item("item2", STGeometry(WGS84_PROJECTION, bbox, periods[2])),
# Fourth time period has no items within the window geometry so it should be skipped.
Item(
"item3",
ST... | Python | 1 |
from paraview.simple import *
from paraview import smtesting
import sys
smtesting.ProcessCommandLineArguments()
# setting the backwards compatibility version for this test, see below
paraview.compatibility.major = 6
paraview.compatibility.minor = 0
def loadRawImage(sourceName, dataType, numDims, dimensions, dataExte... | Python | 1 |
s)):
print os.path.basename(score_files[_it]), ':', weight[_it]
print weight
save_path = './results/summary_final_1_score.npy'
summary_scores(score_files, save_path, weight)
multi_thres_file = use_threshold(save_path)
final_commit_file = replace_leak_write_result(multi_thres_file, show_repl... | Python | 1 |
_KLTWriteFloatImageToPGM(img: FloatImage, filename: *const c_char);
pub fn _KLTWriteAbsFloatImageToPGM(img: FloatImage, filename: *const c_char, scale: c_float);
// pgm
pub fn pgmReadFile(fname: *const c_char, img: *mut c_uchar, ncols: *mut c_int, nrows: *mut c_int) -> *mut c_uchar;
pub fn pgmWriteFil... | Rust | 0 |
import tweepy
import configparser
import streamlit as st
from datetime import datetime
import pytz
# read configs
config = configparser.ConfigParser()
config.read('config.ini')
api_key = 'qZvjrJELbPt0QcyXpoLzTrP64'
api_key_secret = 'Fjilw3PEMNqRLtyNB0CAfDnfWBMaXCAPGLCtWnm59Ar9JBU5wj'
access_token = '1423921567948427... | Python | 1 |
_visible = anim::builder::linear(duration).map(|t| if t <= 0.5 { true } else { false });
let hole_size = Options::new(0.0, MAX_HOLE_SIZE)
.duration(duration.mul_f64(0.5))
.easing(easing::quad_ease())
.build()
.delay(duration.mul_f64(0.5));
drop_size
.zip(drop_p... | Rust | 0 |
ata (for oninput).
// ChangeData actually contains the value of the InputElement/TextAreaElement
// after `change` event occured or contains the SelectElement (see more at the
// variant ChangeData::Select)
/// A type representing change of value(s) of an element after committed by user
/// ([onchange event](https://d... | Rust | 0 |
Ad/baseData/sdTargets)
:param sid `<'int'>`: 领星店铺ID
:param profile_id `<'int'>`: 亚马逊店铺ID (广告帐号ID), 参数来源 `AdsProfiles.profile_id`
:param state `<'str/None'>`: 广告状态, 默认 `None` (查询所有状态), 可选值:
- `"enabled"` (启用)
- `"paused"` (暂停)
- `"archived"` (归档)
:pa... | Python | 1 |
from __future__ import absolute_import, division, print_function
from libtbx.test_utils import show_diff
def exercise():
from mmtbx.ions import utils as ion_utils
import iotbx.pdb
pdb_in = iotbx.pdb.input(source_info=None, lines="""\
CRYST1 20.000 60.000 50.000 90.00 90.00 90.00 P 1
HETATM 1690 ZN ... | Python | 1 |
error::context,
sequence::{
delimited,
preceded,
terminated,
},
Err,
IResult,
};
pub fn parse_nat(from: Span) -> IResult<Span, Literal, ParseError<Span>> {
let (i, base) = opt(preceded(tag("0"), parse_base_code()))(from)?;
let base = base.unwrap_or(Base::_10);
let (upto, bytes) = parse_base_b... | Rust | 0 |
& !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Reader of field `RPT4_RESERVED3`"]
pub type RPT4_RESERVED3_R = crate::R<u8, u8>;
#[doc = "Reader of field `KEY_PURPOSE_5`"]
pub type KEY_PURPOSE_5_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `KEY_PURPOSE_5`"]
pub struct KEY_PU... | Rust | 0 |
urn None,
Some(t) => t,
};
Some(input)
}
pub(crate) fn lens_structure_crate_output_search_dashboards_output_dashboard_summary_list(
input: crate::output::SearchDashboardsOutput,
) -> std::option::Option<std::vec::Vec<crate::model::DashboardSummary>> {
let input = match input.dashboard_summary_l... | Rust | 0 |
val_flag(flag: c_int) -> c_int;
fn af_get_manual_eval_flag(flag: *mut c_int) -> c_int;
fn af_retain_array(out: MutAfArray, arr: AfArray) -> c_int;
fn af_copy_array(out: MutAfArray, arr: AfArray) -> c_int;
fn af_release_array(arr: AfArray) -> c_int;
fn af_print_array(arr: AfArray) -> c_int;
... | Rust | 0 |
#!/usr/bin/env python
#===============================================================================
# gen-unsorted-list.py
#===============================================================================
# Generate random numbers for merge sort benchmark.
#
# -h --help Display this message
# -v --verbose Verb... | Python | 1 |
_message_format():
"""Test that the error message format matches expected pattern."""
with pytest.raises(UserError) as exc_info:
validate_empty_kwargs({'test_arg': 'test_value'})
assert 'Unknown keyword arguments: `test_arg`' in str(exc_info.value)
def test_validate_empty_kwargs_preserves_order()... | Python | 1 |
gen_ty_8 {
IFLA_VLAN_UNSPEC = 0,
IFLA_VLAN_ID = 1,
IFLA_VLAN_FLAGS = 2,
IFLA_VLAN_EGRESS_QOS = 3,
IFLA_VLAN_INGRESS_QOS = 4,
IFLA_VLAN_PROTOCOL = 5,
__IFLA_VLAN_MAX = 6,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct ifla_vlan_flags {
pub flags: __u32,
pub mask: __u32,
}
pub const IFLA_VLAN_QOS_UNSPEC: _bindgen_... | Rust | 0 |
let store_item_2 =
MarketItem::new(14, 11, 4, 5, Rect::new(0, 160, 80, 80), CropType::Potato, 0);
let store_item_3 = MarketItem::new(
21,
15,
6,
7,
Rect::new(0, 240, 80, 80),
CropType::Lettuce,
0,
);
let store_item_4 =
MarketItem::new... | Rust | 0 |
// Assume the parking lane is to the right of us!
CarState::Unparking(_, ref time_int) => raw_body
.shift_right(LANE_THICKNESS * (1.0 - time_int.percent(now)))
.unwrap(),
CarState::Parking(_, _, ref time_int) => raw_body
.shift_right(LANE_T... | Rust | 0 |
l From<CreateNexus> for CreateNexusBody {
fn from(create: CreateNexus) -> Self {
Self {
size: create.size,
children: create.children.into_vec(),
}
}
}
impl From<models::CreateNexusBody> for CreateNexusBody {
fn from(src: models::CreateNexusBody) -> Self {
Self... | Rust | 0 |
(&self) -> bool {
*self == TONADJUSTENR::EN
}
}
#[doc = "Possible values of the field `TONADJUSTPERIOD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TONADJUSTPERIODR {
#[doc = "Adjust done for every 1 3KHz period value."]
HFRC_3KHZ,
#[doc = "Adjust done for every 1 12KHz period value."]
... | Rust | 0 |
"""
Spawn multiple GPS.Process shared between Ada and Python (in this case
git commands) and verify they are freed from memory.
"""
import gc
import GPS
from gs_utils.internal.utils import *
def count_object(typename, objects=None):
if objects is None:
objects = gc.get_objects()
return len([o for o in... | Python | 1 |
'''
# 알고리즘
- 주어진 문제를 해결하기 위한 단계적인 절차를 말한다.
- 컴퓨터에서 어떤 일을 하는 절차를 표현하기 위해 명령어들을 사용하는데, 알고리즘은 특정한 일을 수행하는 명령어들의 집합이다.
- 명령어(instruction set) : 컴퓨터에서 수행되는 문장들을 의미한다.
- 프로그래밍 언어와 상관없이 문제 해결 절차를 나타내는 명령어의 집합이다.
# 알고리즘의 조건
- 입력 : 모호하지 않고 잘 정의된 입력
- 명확성 : 각 명령어의 의미가 모호하지 않고 명확해야 한다.
- 언어 독립성 : 프로그래밍 언어와 상관 없다.
- 출력 : 명확히... | Python | 1 |
import asyncio
from datetime import datetime
from tracker.analytics import AnalyticsEventTypes, analytics
def AnalyticsMiddleware(get_response):
def track_request(request, started, finished):
analytics.track(
AnalyticsEventTypes.REQUEST_SERVED,
{
'timestamp': start... | Python | 1 |
d(url)
inline_urls = processed_urls
# Remove duplicates while preserving order
unique_urls = []
for url in inline_urls:
if url not in unique_urls:
unique_urls.append(url)
# Filter out URLs greater than 300 chars
unique_urls = [url for url in unique_urls if len(url) <= 3... | Python | 1 |
return formatted_results
except Exception as e:
logger.error("vector_search_error", query=query, error=str(e))
return []
def search_graph(self, node_id: str, max_depth: int = 2) -> List[Dict[str, Any]]:
"""Search using graph relationships"""
try:
... | Python | 1 |
import sys
import pytest
from . import util
from numpy.testing import IS_PYPY
class TestBlockDocString(util.F2PyTest):
sources = [util.getpath("tests", "src", "block_docstring", "foo.f")]
@pytest.mark.skipif(sys.platform == "win32",
reason="Fails with MinGW64 Gfortran (Issue #9673)")... | Python | 1 |
funding_file = "../../data/binance_btcusdt_funding.csv"
btc_position = 5 # Your initial BTC balance
position_fee = 0.0002 # Maker fee (0.02%)
use_compounding = True # Reinvest profits in BTC or not
| Python | 1 |
import asyncio
import os
import re
import aiofiles
from pykeyboard import InlineKeyboard
from pyrogram import filters
from pyrogram.types import InlineKeyboardButton
from aiohttp import ClientSession
from VIP_INNOCENT import app
from VIP_INNOCENT.utils.errors import capture_err
from VIP_INNOCENT.utils.pastebin import... | Python | 1 |
db.add(ssl_cert)
# Domain'in SSL durumunu güncelle
domain.ssl_enabled = True
domain.ssl_expiry = ssl_cert.expiry_date
db.commit()
return {"message": "SSL certificate installed successfully"}
else:
raise HTTPExc... | Python | 1 |
Download Markdown",
data=md_content,
file_name="requirements.md",
mime="text/markdown",
use_container_width=True
)
with col3:
# Validation report download
validation_json = json.dumps(validation_report,... | Python | 1 |
, 78, 68, 174, 66, 96, 130];
assert_eq!(output, expected);
}
#[test]
#[cfg(feature = "pngio")]
fn write_rgb_png() {
let rgb_data: Vec<u8> = vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 127,
127, 127];
let mut image = Image::new(PixelFormat::RGB, 2, ... | Rust | 0 |
hanged_listener(&mut self, mut listener: mem::ManuallyDrop<Box<WlListener<CompositorRef>>>) {
unsafe { weston_compositor_add_heads_changed_listener(self.as_ptr(), &mut listener.wll); }
}
pub fn iterate_heads(&mut self) -> HeadIterator {
HeadIterator {
compositor: self,
h... | Rust | 0 |
ulaBuilder, Pos3},
sim::mcrt::{EngineBuilder, FilmBuilder},
};
use arctk_attr::file;
use ndarray::Array3;
use std::{
fmt::{Display, Formatter},
path::{Path, PathBuf},
};
/// Engine selection.
#[file]
pub enum EngineBuilderLoader {
/// Standard sampling engine.
Standard,
/// Raman engine.
Ra... | Rust | 0 |
# Obtained from: https://github.com/open-mmlab/mmsegmentation/tree/v0.16.0
# Modifications:
# - BN instead of SyncBN
# - Removed auxiliary decoder
# model settings
norm_cfg = dict(type='BN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained='open-mmlab://resnet50_v1c',
backbone=dict(
... | Python | 1 |
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::process::exit;
use structopt::StructOpt;
#[derive(StructOpt)]
struct Cli {
#[structopt(parse(from_os_str))]
path: std::path::PathBuf,
}
pub fn lines_from_file<T: AsRef<Path>>(filename: T) -> String {
let file = std::fs::File::open(&filename);... | Rust | 0 |
<Response<'static>, HecateError> {
let conn = conn.get()?;
auth_rules.allows_feature_get(&mut auth, &*conn)?;
match feature::get(&*conn, &id) {
Ok(feature) => {
let feature = geojson::GeoJson::from(feature).to_string();
let mut response = Response::new();
respo... | Rust | 0 |
SSED_PREFIX):
compressed = False
h = decode_base58(private_key)
if double_sha256(h[:-4])[:4] != h[-4:]:
raise Exception()
private_key = h[1:33]
except:
try:
private_key = bytes_from_he... | Python | 1 |
::dx_dxgi_format_dds = 7;
pub const dx_dxgi_format_dds_DXGI_FORMAT_R32G32B32_SINT: root::gli::dx_dxgi_format_dds = 8;
pub const dx_dxgi_format_dds_DXGI_FORMAT_R16G16B16A16_TYPELESS:
root::gli::dx_dxgi_format_dds = 9;
pub const dx_dxgi_format_dds_DXGI_FORMAT_R16G16B16A16_FLOAT: root::... | Rust | 0 |
"""
team: Unathletic Avengers
teacher: Brother Keers
file : team_10.py
assignment: track bank accounts and the balances in each one.
"""
print("""
.!!!!.
.&@@@@^
... ^&@@@@@^
^... | Python | 1 |
os2,
key_vel2,
pR_model,
sdf,
cost_sigma,
epsilon_dist,
Qc_model,
delta_t,
tau,
))
use_trustregion_opt = Tr... | Python | 1 |
from_impl!(String, String);
from_impl!(Vec<u8>, ByteArray);
from_impl!(bool, Enum => |v| v != 0);
from_impl!(u8,
UnsignedInt8 => u8::from,
UnsignedInt8z => u8::from,
ByteArray => |v: Vec<u8>| {
if v.len() != 1 {
panic!("u8 can only come from a 1-element ByteArray");
}
v... | Rust | 0 |
slices
pub affine_lowpad:usize, // padding for affine subswath computation
pub affine_highpad:usize,
pub affine_var_norm:f64,
pub burst_padding:usize, //Burst padding when processing segments
pub scs_normalize:u32,
pub scs_scale:f64,
pub scs_rho_x:f64,
pub scs_max_iters : u32,
p... | Rust | 0 |
from dataclasses import dataclass
from typing import List
from flask import request
from pre_award.authenticator.models.data import get_data
from pre_award.authenticator.models.round import Round
from pre_award.common.locale_selector.get_lang import get_lang
from pre_award.config import Config
@dataclass
class Fund... | Python | 1 |
# 模型选择
custom_openai_options = [
"gpt-4o",
"gpt-4o-mini",
"gpt-4-turbo",
"gpt-4",
"gpt-3.5-turbo",
"claude-3.5-sonnet",
"claude-3-opus",
"claude-3-sonnet",
"clau... | Python | 1 |
import cv2
import rospy
import time
from threading import Thread
from .camera import Camera
import numpy as np
from std_msgs.msg import String
import serial
class Action():
def __init__(self, shoot_topic, baudrate) -> None:
self.result = 0
self.serial_port = serial.Serial(shoot_topic, baudrate)
... | Python | 1 |
BOptions::new();
let mut causet_opts = PrimaryCausetNetworkOptions::new();
causet_opts.set_level_zero_file_num_compaction_trigger(10);
let f = Box::new(ConePropertiesCollectorFactory::default());
causet_opts.add_Block_properties_collector_factory("edb.size-collector", f);
let cau... | Rust | 0 |
self, input: impl Into<std::string::String>) -> Self {
self.delegation_set_id = Some(input.into());
self
}
/// <p>If you're using reusable delegation sets and you want to list all of the hosted zones that are associated
/// with a reusable delegation set, specify the ID o... | Rust | 0 |
from fastapi import APIRouter
from DashAI.back.api.api_v1.endpoints import (
components,
converters,
datasets,
experiments,
explainers,
explorers,
generative_process,
generative_session,
jobs,
notebook,
pipelines,
plugins,
predict,
runs,
)
api_router_v1 = APIRou... | Python | 1 |
y, self.z - other.z)
}
fn manhattan_distance(self, other: Self) -> usize {
let c = self.sub(other);
(c.x.abs() + c.y.abs() + c.z.abs()) as usize
}
}
#[derive(Debug)]
struct DetectionCube {
scanners: HashSet<Coordinate>,
beacons: HashSet<Coordinate>,
}
impl DetectionCube {
fn n... | Rust | 0 |
();
res.extend_from_slice(&[
0xa0, 0x04, 0x03, 0x02, 0x01, 0x80, 0xff, 0x2a, 0x2a, 0x0a, 0xf1, 0xa3, 0x6a, 0x05, 0xd0,
0x12, 0x5f, 0x88, 0x5d, 0x88, 0x1d, 0x49, 0xe1,
]);
res
}
fn data_payload_with_fport_zero() -> Vec<u8> {
let mut res = Vec::new();
res.extend_from_slice(&[
... | Rust | 0 |
# SPDX-License-Identifier: Apache-2.0
import pytest
from pathlib import Path
pw = pytest.importorskip("playwright.sync_api")
from playwright.sync_api import sync_playwright # noqa: E402
from playwright._impl._errors import Error as PlaywrightError # noqa: E402
DEF_GEN = 3
def _run_sim(page):
page.evaluate("d... | Python | 1 |
=> lda::<IndirectX>,
0xb1 => lda::<IndirectY>,
0xa2 => ldx::<Immediate>,
0xa6 => ldx::<ZeroPage>,
0xb6 => ldx::<ZeroPageY>,
0xae => ldx::<Absolute>,
0xbe => ldx::<AbsoluteY>,
0xa0 => ldy::<Immediate>,
0xa4 => ldy::<ZeroPage>,
0xb4 => ldy::<ZeroPageX>,
0xac => ldy::<Absolute>,
0xbc => ldy::<Abso... | Rust | 0 |
".notdef",
".notdef",
".notdef",
".notdef",
".notdef",
".notdef",
".notdef",
"dotlessi",
"quoteleft",
"quoteright",
"circumflex",
"tilde",
"macron",
"breve",
"dotaccent",
"dieresis",
".notdef",
"ring",
"cedilla",
".notdef",
"hungarumlaut",
... | Rust | 0 |
);
q_pos.push_back(i);
let mut min_val = q_min_val;
let mut min_pos = q_min_pos;
let mut new_minim = new_minimizer;
if min_pos == popped_index.unwrap() as i32 {
min_val = u64::max_value();
min_pos = i as i32;
for j in (0..q.len()).rev() {
if q[j] < min_val {
... | Rust | 0 |
# Make a Python script that logs in to this page:
# http://target1.bowneconsulting.com/protected/A2.4
# with these parameters:
# Username: admin
# Password: a two-digit number
# User-Agent: python
# The server will reply with a flag.
import requests
# Input
url = 'http://target1.bowneconsulting.com/protected/A2.4'
... | Python | 1 |
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
def start_parser(text):
data = {}
s = BeautifulSoup(text, "lxml")
photo_category_nodes = s.select('#content .article .mod')
for photo_category_node in photo_category_nodes:
photo_category_name = photo_category_node.find(
... | Python | 1 |
f the tilemap
y = cam_pos_y_tile/16 - 2
for row in game_map:
x = cam_pos_x_tile/16 - 2
for tile in row:
if int(tile) > 2:
display.blit (block, (x*0.5*width+y*-0.5*width , x*0.25*height+y*0.25*height))
x += 1
y += 1
#renders the 4th layer of the tilemap
y = cam_pos_y_tile/16 - ... | Python | 1 |
tr();
//! let change_descriptor = cli_opt.change_descriptor.as_deref();
//!
//! let database = MemoryDatabase::new();
//!
//! let config = match cli_opt.esplora {
//! Some(base_url) => AnyBlockchainConfig::Esplora(EsploraBlockchainConfig {
//! base_url: base_url.to_string(),
//! concurrency: Some(cl... | Rust | 0 |
udata: $data as UData,
}
};
}
pub struct MioKQueueSelector {
id: usize,
kq: RawFd,
}
trait IsMinusOne {
fn is_minus_one(&self) -> bool;
}
impl IsMinusOne for i32 {
fn is_minus_one(&self) -> bool {
*self == -1
}
}
impl IsMinusOne for isize {
fn is_minus_one(&self... | Rust | 0 |
from numpy.core.defchararray import mod
from sklearn.svm import SVC
import numpy as np
import matplotlib.pyplot as plt
def show_samples(ax, X, Y):
for i in range(Y.shape[0]):
if (Y[i] == 1):
ax.scatter(X[i,0], X[i,1], marker='^', color='r')
else:
ax.scatter(X[i,0], X[i,1], ... | Python | 1 |
import json
import requests
from lib.core.common import random_num, get_replaced_url, vuln_print
from urllib import parse
import time
from lib.settings import vuln_level
class SQLITimeCheck:
def __init__(self):
self.sleep_str = "5"
self.num = random_num(4)
self.sql_time_payloads = {
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.