text string | label_name string | labels int64 |
|---|---|---|
_impl_trait)]
// check-pass
fn main() {}
type NoReveal = impl std::fmt::Debug;
fn define_no_reveal() -> NoReveal {
""
}
fn no_reveal(x: NoReveal) {
let _: &'static str = x;
let _ = x as &'static str;
}
<reponame>g-logunov/polars
mod apply;
pub mod dataframe;
pub mod dsl;
pub mod utils;
pub use apply::*;... | Rust | 0 |
"];
let endpoints = urls
.iter()
.map(|s| SensitiveUrl::parse(s).unwrap())
.collect::<Vec<_>>();
let mut endpoint_arg = urls[0].to_string();
for url in urls.into_iter().skip(1) {
endpoint_arg.push(',');
endpoint_arg.push_str(url);
}
// this is way better but i... | Rust | 0 |
status which is going to be set to notify the guest.
($fn:ident, $property:ident, $int:ident) => {
fn $fn(&mut self, value: u32) -> bool {
let old = std::mem::replace(&mut self.$property, value);
old != self.$property && self.set_int_status($int)
}
};
}
impl GoldfishBat... | Rust | 0 |
v1.get_x() - v2.get_x(),
v1.get_y() - v2.get_y(),
v1.get_z() - v2.get_z(),
v3.get_x() - v2.get_x(),
v3.get_y() - v2.get_y(),
v3.get_z() - v2.get_z()
);
let norm2:(f64,f64,f64) = process_3d::calc_norm(
v2.get_x() - v1.get_x(),
v2.get_y() - v1.get_y(),
... | Rust | 0 |
starts = self._codegen.map_ast_to_pos.get(node.variable, None)
if starts is None:
return []
elif isinstance(node, CFunctionCall):
starts = self._codegen.map_ast_to_pos.get(
node.callee_func if node.callee_func is not None else node.callee_target, No... | Python | 1 |
"""
Advanced examples for pretraining.
"""
| Python | 1 |
|| Utc::now().timestamp() >= deadline)
&& self.workers.count() > 0
{
{
debug!("resend updated block");
let mut wallet_listener_url: Option<String> = None;
if !config.burn_reward {
wallet_listener_url = Some(config.wallet_listener_url.clone());
}
// If this is a new block, clea... | Rust | 0 |
5d9f3b
h = ((h >> 16) ^ h) & 255
return mr(n, [_MR_BASES_32[h]])
if n < 350269456337:
return mr(n, [4230279247111683200, 14694767155120705706, 16641139526367750375])
if n < 55245642489451:
return mr(n, [2, 141889084524735, 1199124725622454117, 11096072698276303650])
if n < 79... | Python | 1 |
t_scope_access()
step2_function_based_access()
step3_practical_patterns()
scope_summary()
print("🎯 KEY TAKEAWAYS:")
print(" • Python can directly access local: and public: scopes")
print(" • private: and system: scopes need function-based access")
print(" • Use scopes to control data vi... | Python | 1 |
cast_rgba_f32(x: [f32; 4]) -> Self::Output;
}
impl<'a, A> CastingIter<'a, A> {
pub(crate) fn new(iter: ReadColors<'a>) -> Self {
CastingIter(iter, PhantomData)
}
/// Unwrap underlying `ReadColors` object.
pub fn unwrap(self) -> ReadColors<'a> {
self.0
}
}
impl<'a, A: Cast> ExactS... | Rust | 0 |
per1 = int(input("ENter the age of person1 :"))
per2 = int(input("ENter the age of person2 :"))
per3 = int(input("ENter the age of person3 :"))
per4 = int(input("ENter the age of person4 :"))
if per1 > per2 and per1 > per3 and per1 > 4:
print("Person1 is oldest")
elif per2 > per3 and per2 > per4:
print("person... | Python | 1 |
s[bp].bound = Bound(
30,
remaining_width.max - 30 * (flex_columns + auto_columns),
)
else:
# we use flex-columns exclusively, therefore subdivide the remaining width
for column in self:
... | Python | 1 |
c": 3}, "b": 2}"#,
None,
Some(r#"["a", "b"]"#),
true,
),
// Tests with path expression
(r#"{"a": 1}"#, Some("$.a"), None, true),
(
r#"{"a": {"c": 3}, "b": 2}"#,
Some("$.a"),
So... | Rust | 0 |
lex( s );
assert_eq!( 1, o.len() );
assert_eq!( r, o[0] );
}
}
#[test]
fn should_handle_symbol() {
let symbols = vec! [ ("symbol", Token::Symbol("symbol".to_owned()))
, ("symbol123", Token::Symbol("symbol123".to_owned()))
... | Rust | 0 |
if p.metadata.uid != pod.metadata.uid:
pending_pods.remove(pod)
continue
logger.debug(
f"Pod '{p.metadata.name}' still around in phase:"
f" {p.status.phase}"
)
... | Python | 1 |
#Python es un lenguaje con una amplia gama de estructuras de datos.
#Listas, son mutables y aceptan datos de cualquier tipo mezclados, están indexados y no poseen un tamañó fijo
lista = [1, True, "hola"]
print(lista[0])
lista.append(2)
print(lista)
lista.pop(3)
print(lista)
lista.remove("hola")
print(lista)
l... | Python | 1 |
::Red),
"green" => Some(LedColor::Green),
"blue" => Some(LedColor::Blue),
"amber" => Some(LedColor::Amber),
"violet" => Some(LedColor::Violet),
"yellow" => Some(LedColor::Yellow),
"ir" => Some(LedColor::Ir),
"multi" => Some(LedColor::Mu... | Rust | 0 |
import json
import random
from pathlib import Path
from urllib.request import urlretrieve
from llm_jp_eval.jaster.base import BaseDatasetProcessor, Sample
class JNLIDatasetProcessor(BaseDatasetProcessor):
data_name = "jnli"
def __init__(self, dataset_dir: Path, version_name: str) -> None:
super().__... | Python | 1 |
'japonský'
; 'Dutch'
; 'Norwegian'
; 'Portuguese'
'russian' 'ruský'
'swedish' 'švédsky'
; 'Turkish'
'slovak' 'slovenský'
#endif
#if Language == #sv "swedish"
; 'Afrikaans' 'Afrikaans'
'Arabic' 'Arabiska'
'Chinese' 'Kinesiska'
'Chi... | Rust | 0 |
amepad => "gamepad",
SpeakerSelection => "speaker-selection",
InterestCohort => "interest-cohort",
ConversionMeasurement => "conversion-measurement",
FocusWithoutUserActivation => "focus-without-user-activation",
Hid => "hid",
IdleDetection => "id... | Rust | 0 |
fmt(&self, args: std::fmt::Arguments<'_>) {
use py_io::Write;
let vm = self.0;
if let Ok(stderr) = get_stderr(vm) {
let mut stderr = py_io::PyWriter(stderr, vm);
if let Ok(()) = stderr.write_fmt(args) {
return;
}
}
eprint!("{}"... | Rust | 0 |
}
/*#[derive(Deserialize)]
/// The Columns struct
pub struct Columns {
/// The columns
columns: Vec<Column>
}*/
/// Expects an empty `<column …/>` tag or a closing `</columns>` tag
pub fn expect_column_or_end_columns<B: BufRead>(
xml: &mut Reader<B>,
buf: &mut Vec<u8>,
) -> Result<Option<Column>, XmlE... | Rust | 0 |
c_uint = 0x84DA as c_uint;
pub const TEXTURE27: c_uint = 0x84DB as c_uint;
pub const TEXTURE28: c_uint = 0x84DC as c_uint;
pub const TEXTURE29: c_uint = 0x84DD as c_uint;
pub const TEXTURE30: c_uint = 0x84DE as c_uint;
pub const TEXTURE31: c_uint = 0x84DF as c_uint;
pub const ACTIVE_TEXTU... | Rust | 0 |
viceSize {
debug_assert_eq!(self.size() % mem::size_of::<T>() as DeviceSize, 0);
self.size() / mem::size_of::<T>() as DeviceSize
}
/// Reduces the slice to just one element of the array.
///
/// Returns `None` if out of range.
#[inline]
pub fn index(self, index: DeviceSize) -> O... | Rust | 0 |
om_state=0, learning_rate=lr, n_estimators=n_estimators, subsample=subsample, max_depth=max_depth, alpha=alpha/2, loss='quantile')
mean.fit(X_train, y_train)
upper.fit(X_train, y_train)
lower.fit(X_train, y_train)
pred_mean = mean.predict(X_train)
pred_upper ... | Python | 1 |
)
return {"isError": True}
# Update transcript.txt with the filename and text
transcript_path = os.path.join(samples_dir, "transcript.txt")
with open(transcript_path, "a") as transcript_file:
transcript_file.write(f"samples/{final_f... | Python | 1 |
languages = {
"c#": 1,
"csharp": "c#",
"vb.net": 2,
"vb": 2,
"visual_basic_dotnet": 2,
"f#": 3,
"fsharp": 3,
"java": 4,
"python2": 5,
"py2": 5,
"c_gcc": 6,
"gcc": 6,
"c": ["gcc", "clang", "visual_c"],
"cplusplus_gcc": 7,
"cplusplus": "c++",
"g++": 7,
"... | Python | 1 |
img[1][height - 1] = 255
img[2][height - 1] = 0
img[3][height - 1] = 255
img[1][height - 2] = 0
img[2][height - 2] = 255
img[3][height - 2] = 0
img[1][height - 3] = 255
img[2][height - 3] = 0
img[3][height - 3] = 0
return img
def _ra... | Python | 1 |
erloading. I think this can be detected by checking for a
// `type_dependent_defs` entry on a non-`MethodCall` node. (Alternative: rewrite this
// whole analysis to run over MIR. At that level, operator-overload method calls are fully
// explicit.)
match e.kind {
ExprKind... | Rust | 0 |
import scipy.signal as signal
import numpy as np
from pydub import AudioSegment
import os
# Load the audio file
audio = AudioSegment.from_file('audio_file.mp3')
rate = audio.frame_rate
data = np.array(audio.get_array_of_samples())
# Define the high-pass filter
cutoff_freq = 500 # Hz
nyquist_freq = 0.5*rate
order = 5
... | Python | 1 |
import signal
import time
from typing import Dict
import openai
from openai.types.chat import ChatCompletion
def make_request(
client: openai.Client,
message: str,
model: str,
max_tokens: int = 512,
temperature: float = 1,
n: int = 1,
**kwargs
) -> ChatCompletion:
# print ("model", mo... | Python | 1 |
# This file was auto-generated by Fern from our API Definition.
import typing
import typing_extensions
from ..types.gift_card_activity_redeem_status import GiftCardActivityRedeemStatus
from .money import MoneyParams
class GiftCardActivityRedeemParams(typing_extensions.TypedDict):
"""
Represents details abou... | Python | 1 |
zeSeq, Serializer};
use smallvec::SmallVec;
use std::ffi::CStr;
use std::os::raw::c_char;
use std::ptr::NonNull;
// https://tools.ietf.org/html/rfc7159#section-6
// "[-(2**53)+1, (2**53)-1]"
const STRICT_INT_MIN: i64 = -9007199254740991;
const STRICT_INT_MAX: i64 = 9007199254740991;
pub const STRICT_INTEGER: u8 = 1;
... | Rust | 0 |
dCode::MSP_EEPROM_WRITE as u16,
direction: MspPacketDirection::ToFlightController,
data: vec![],
};
let write_fn = async {
if &self.core.buff_size() == &0 {
self.core.write(packet).await;
return Ok(());
}
retur... | Rust | 0 |
:
str: The formulated prompt based on the provided configuration and data.
"""
all_needed_variable_name = get_config_needed_variables(prompt_config)
# Retrieve information from the SOP, i.e., the configuration
data_dict_for_prompt = {
"sop_config": sop.get_dict_for_sop_optimizer(),
... | Python | 1 |
where
T: BorshSchema,
E: BorshSchema,
{
fn add_definitions_recursively(definitions: &mut HashMap<Declaration, Definition>) {
let definition = Definition::Enum {
variants: vec![
("Ok".to_string(), T::declaration()),
("Err".to_string(), E::declaration()),
... | Rust | 0 |
from .base_page import BasePage
from .locators import ProductPageLocators
class ProductPage(BasePage):
def add_to_basket(self):
button = self.browser.find_element(*ProductPageLocators.BUTTON_ADD_BASKET)
button.click()
def check_right_title(self):
right_product = self.browser.find_ele... | Python | 1 |
from libraries import *
############################## data normilization #################################
#data normilizations
def norm_mean_std(data):
x=list(data.shape)
notchedData=np.zeros((x))
for i in range (len(data)):
temp=data[i]
for j in range (8):
temp1=temp[j,:]
... | Python | 1 |
l_names"][key_label])] = 1
tmp_label = 1 - tmp_label
label_guidances[key_label] = json.dumps(
self._apply(tmp_label, self.sid.get(key_label)).astype(int).tolist()
)
d[self.guidance] = label_guidances
... | Python | 1 |
=> c,
None => return Err(DrawError::VerticesSourcesLengthMismatch)
};
unsafe {
if let Some(instances_count) = instances_count {
ctxt.gl.DrawArraysInstanced(primitives.to_glenum(), base_vertex,
... | Rust | 0 |
("cop", (0, 0)),
("Emacr", (0, 0)),
("rAr", (0, 0)),
("Mopf;", (120132, 0)),
("LeftDownTeeVe", (0, 0)),
("LessEqu", (0, 0)),
("twi", (0, 0)),
("Odblac;", (336, 0)),
("nsq", (0, 0)),
("gvertneqq;", (8809, 65024)),
("prop;", (8733, 0)),
... | Rust | 0 |
for.
///
/// Note: This is only available for DS3232 and DS3234 devices.
pub fn set_temperature_conversion_rate(
&mut self,
rate: TempConvRate,
) -> Result<(), Error<E, ()>> {
let status = match rate {
TempConvRate::_64s => self.status & !BitFlags::CRATE1 & !BitFlags... | Rust | 0 |
"""
CS5001 Fall 2022
Final Project: Brain Tumor Segmentation
- A customized U-Net model
Hua Wang
"""
from unet.mylib import *
from torchinfo import summary
class Unet(nn.Module):
"""
A U-Net model
"""
def __init__(self, in_channel):
"""
Constructor -- create a new inst... | Python | 1 |
rtexAttributeValues::Float32x3(mesh.positions),
);
render_mesh.set_attribute("Vertex_Normal", VertexAttributeValues::Float32x3(mesh.normals));
render_mesh.set_attribute(
"Vertex_Uv",
VertexAttributeValues::Float32x2(vec![[0.0; 2]; num_vertices]),
);
render_mesh.set_indices(Some(Indic... | Rust | 0 |
enum parent to implement [`From`] for.
///
/// - `#[thalo(variant = "...")]`
///
/// The variant of the parent enum that holds this struct.
///
/// # Examples
///
/// ```
/// use thalo::event::Event;
///
/// pub enum AuthEvent {
/// LoggedIn(LoggedInEvent),
/// Registered(RegisteredEvent),
/// }
///
/// #[de... | Rust | 0 |
(lon - self.transform[4]) / self.transform[0]
r = (lat - self.transform[5]) / self.transform[3]
return (r, c)
def get(self, band, r, c):
'''Fetch the selected pixel from the selected band.'''
return self.images[band][r, c]
def get(self, r, c):
'''Fetch the selected ... | Python | 1 |
//Internal and may change without warning.
pub fn from_reader(reader: HttpReader<&'a mut BufReader<&'b mut NetworkStream>>, headers: &Headers) -> BodyReader<'a, 'b> {
use header::ContentType;
use mime::{Mime, TopLevel, SubLevel, Attr, Value};
let boundary = match headers.get() {
... | Rust | 0 |
isc_id, track_id, o);
}
}
}
}
// check tags
if let Some(path) = manager.check_tags_loop() {
log::error!(target: "repo|tags", "Loop detected: {:?}", path);
has_error = true;
}
if !has_error {
info!(target: "anni", "{}", fl!("repo-validate-en... | Rust | 0 |
"
@version #[nightly] "nightly"
@feature rcpc
@detect "rcpc"
@version #[nightly] "nightly"
@feature dotprod
@detect "dotprod"
@version #[nightly] "nightly"
}
#[cfg(all(target_arch = "mips"))]
features! {
@detect_macro is_mips_feature_detected
@feature msa
@detect "msa"
@v... | Rust | 0 |
aining: self.remaining,
}
}
}
pub struct ScanParseFinal<'a, T>
{
tuple: T,
to_parse: &'a str,
}
impl<'a, T> ScanParseFinal<'a, T>
{
pub fn parse<V>(self) -> T::ResultType
where T: TupleAppend<V>,
V: 'static + Debug + FromStr,
V::Err: Debug
{
let pars... | Rust | 0 |
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 CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, AR... | Rust | 0 |
0.4 build-2249910, 32-bit Ubuntu x86 guest,
// single-stepping does not trigger watchpoints :-(. So we have to
// check watchpoints here. fast_forward also hides watchpoint changes.
// Write-watchpoints will detect that their value has changed and trigger.
// XXX Read/exec watchpoints can't be detected ... | Rust | 0 |
akingkeyindex", Some(0))?;
write_pubkey(
&self.storage,
&stakingkeyset_keyspace,
&redeemaddress,
&staking_key,
)?;
write_pubkey(
&self.storage,
&stakingkey_keyspace,
&format!("{}", index_value),
&st... | Rust | 0 |
AD2<MODE>; // <- big pad 2
pub type EDGE08<MODE> = p0::P0_18<MODE>;
pub type EDGE09 = COL7;
pub type EDGE10 = COL3;
pub type EDGE11 = BTN_B;
pub type EDGE12<MODE> = p0::P0_20<MODE>;
pub type EDGE13<MODE> = PAD3<MODE>; // <- big pad 3
pub type EDGE14<MODE> = SCK<MODE>;
pub type EDGE15<MODE> = MISO<MODE>;
pub type EDGE16... | Rust | 0 |
Option<(Option<Bno08xRvcRawFrame>, usize)> {
let mut release_size = 0;
for (idx, iter) in raw_bytes.iter().enumerate() {
match self.state {
State::LookingForFirstHeaderByte => {
if *iter == (BNO08X_UART_RVC_HEADER >> 8) as u8 {
self... | Rust | 0 |
ty::AutoDerefRef {
autoref: Some(_), ..})) => {
// Equivalent to &*expr or something similar.
// Result is an rvalue.
let expr_ty = ty::expr_ty_adjusted(self.tcx, expr);
self.cat_rvalue_node(expr, expr_ty)
}
... | Rust | 0 |
js_code.append('%s = (%s);' % (alias, code))
if es6:
emit(js2py.translate_js6('\n'.join(js_code)))
else:
emit(js2py.translate_js('\n'.join(js_code)))
emit('class TransformNearley(Transformer):')
for alias in n2l.alias_js_code:
emit(" %s = var.get('%s').to_python()" % (ali... | Python | 1 |
from PIL import Image
from maskrcnn_benchmark.data.datasets.coco import COCODataset
from maskrcnn_benchmark.data.datasets.closeup import CloseupDataset
import os
#crop the object from original image and save them in original shape
#save object under categorized folders
#here we do not crop the original size, but crop... | Python | 1 |
info.get("symbol", "N/A"), inline=True)
embed.add_field(name="👤 Developer", value=f"[{developer_address[:8]}...](https://explorer.solana.com/address/{developer_address})", inline=True)
# Add image if available
if image_url:
embed.set_thumbnail(url=image_url)
else:
embed... | Python | 1 |
data, 254_f64);
assert!(result.is_ok());
assert_eq!(data, [0xAFu8, 0xEBu8]);
}
/* TEST SIGNED */
#[test]
fn test_decode_signed_001() {
let sig = Signed::new(0, 8, 1.0, 0.0, Endian::Little).unwrap();
let data = [0b0111_1111];
let decode = sig.try_decode(&data);... | Rust | 0 |
def cleanup(self, return_onnx=False):
self.graph.cleanup().toposort()
if return_onnx:
return gs.export_onnx(self.graph)
| Python | 1 |
import os
import re
import py2neo
from tqdm import tqdm
import argparse
import pandas as pd
from datetime import datetime
import numpy as np
def safe_split(value, delimiter='/'):
if pd.isna(value):
return []
if isinstance(value, str):
return [v.strip() for v in value.split(delimiter)]
retu... | Python | 1 |
#
# # var = 10
# # print(var/0)) # eroare de sintaxa
# # print(var/0) # eroare de exceptie
#
# """ Raise Exception """
#
# # var = 10
# # if var >= 5:
# # raise Exception('Aici este o eroare')
#
#
# """ blocul try / except """
#
# # # ex:
# # my_text = input('Introduceti un nr.: ')
# # # value = int(my_text)
# # t... | Python | 1 |
Debug, PartialEq, Copy, Clone, Serialize, Deserialize)]
pub struct GroupEpoch(pub u64);
impl GroupEpoch {
pub fn increment(&mut self) {
self.0 += 1;
}
}
impl Codec for GroupEpoch {
fn encode(&self, buffer: &mut Vec<u8>) -> Result<(), CodecError> {
self.0.encode(buffer)?;
Ok(())
... | Rust | 0 |
panded to:
"node <name>(defined at <path>)".
Args:
error_message: A string to interpolate.
graph: ops.Graph object containing all nodes referenced in the error
message.
Returns:
The string with tags of the form {{type name}} interpolated.
"""
seps, tags = parse_message(error_message)
s... | Python | 1 |
),DynamicDictKeysIterator::reversed(slf.inner.clone()))
}
}
#[cfg(feature="python_skills")]
#[pyproto]
impl PyMappingProtocol for DynamicDict {
fn __delitem__(&mut self, key: &str) -> PyResult<()> {
self.map.lock_it().remove(key).ok_or(PyErr::new::<PyAttributeError, _>(
format!("Key: {} wa... | Rust | 0 |
in_at
)
class LoginResponse(BaseModel):
"""Login response schema"""
user: UserResponse
access_token: str
refresh_token: str
token_type: str = "bearer"
class RegisterResponse(BaseModel):
"""Register response schema"""
user: UserResponse
access_token: str
refresh_token: str... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Softhealer Technologies.
from odoo import models
class PosOrder(models.Model):
_inherit = "pos.order"
def sh_receipt_send_by_email(self):
self.ensure_one()
ir_model_data = self.env['ir.model.data']
try:
template_id = ir_model_data._xmlid_t... | Python | 1 |
import mysql
import ping3
import time
from datetime import datetime
import mysql.connector
# Configuración de conexión a la base de datos
DB_CONFIG = {
'database': 'dbinventario', # Cambia 'dbname' a 'database'
'user': 'root',
'password': '0506',
'host': 'localhost',
'port': '3306' # Puerto por ... | Python | 1 |
ISTANCE_CALIBRATION)
///
/// Required feature: android-hardware-camera2-CameraCharacteristics_Key
#[cfg(any(feature = "all", feature = "android-hardware-camera2-CameraCharacteristics_Key"))]
pub fn LENS_INFO_FOCUS_DISTANCE_CALIBRATION<'env>(env: &'env __jni_bindgen::Env) -> __jni_bindgen... | Rust | 0 |
pub news_rx: Option<Receiver<NewsCardData>>,
}
impl Headlines {
pub fn new() -> Self {
// temporary sample
let config: HeadlinesConfig = confy::load("headlines").unwrap_or_default();
Headlines {
articles: vec![],
api_key_inited: !config.api_key.is_empty(),
... | Rust | 0 |
import math
from django.db import transaction
from django.core.management.base import BaseCommand
from poker.constants import SEASONS
from rewards.models import Badge
from ui.views.leaderboard import top_users_by_winnings
class Command(BaseCommand):
help = 'Award Season 0 leaderboard badges'
def handle(sel... | Python | 1 |
unsafe {
let mask = nfs_umask(self.context, mask);
Ok(mask)
}
}
pub fn unlink(&self, path: &Path) -> Result<()> {
let path = CString::new(path.as_os_str().as_bytes())?;
unsafe {
check_retcode(self, nfs_unlink(self.context, path.as_ptr()))?;
... | Rust | 0 |
REG_GPIO_28_PD_W { w: self }
}
#[doc = "Bit 4 - Pull Up Resistor for GPIO28."]
#[inline(always)]
pub fn reg_gpio_28_pu(&mut self) -> REG_GPIO_28_PU_W {
REG_GPIO_28_PU_W { w: self }
}
#[doc = "Bits 2:3 - Driving control enabled for GPIO28."]
#[inline(always)]
pub fn reg_gpio_... | Rust | 0 |
;
pub use super::HCTSIZ0::XFRSIZ;
}
#[repr(C)]
pub struct RegisterBlock {
/// OTG_FS host configuration register (OTG_FS_HCFG)
pub HCFG: RWRegister<u32>,
/// OTG_FS Host frame interval register
pub HFIR: RWRegister<u32>,
/// OTG_FS host frame number/frame time remaining register (OTG_FS_HFNUM)... | Rust | 0 |
nts {
value: None,
size: Some(Constraint::new(None, Some(3))),
}).unwrap();
assert_eq!(v.len(), target.len());
for i in 0..v.len() {
assert_eq!(v[i], target[i]);
}
}
#[test]
fn decode_sequence_of_short_bit_string() {
let data = b"\x02\xee";
let mut d = aper::Decoder::new... | Rust | 0 |
import pybbt as p
import helpers as h
@p.subcase()
def acl():
src = h.Redis()
dst = h.Redis()
src.client.execute_command("acl", "setuser", "user0", ">password0", "~*", "+@all")
src.client.execute_command("acl", "setuser", "user0", "on")
src.client.execute_command("auth", "user0", "password0") #... | Python | 1 |
from impacket.smbconnection import SMBConnection
from impacket.smb import SMBCommand
from impacket.smb3structs import *
import socket
import struct
# Constants for the exploit
SMB_PORT = 445
def create_exploit_packet(target_ip):
# Create a malformed SMB packet to trigger the buffer overflow
# This part is hig... | Python | 1 |
):
command: CommandInfo # = Field(description="Информация о команде")
code: str # = Field(description="Код ошибки")
details: str # = Field(description="Сообщение об ошибке")
class RequestType(str, Enum):
TEXT_REQUEST = "text_request"
ERROR = "error"
SUCCESS = "success"
class RequestPay... | Python | 1 |
import time
from bs4 import BeautifulSoup
import logging
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdrive... | Python | 1 |
"""
WSGI config for project_jsonrpc project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJAN... | Python | 1 |
QMessageBox.critical(self, "Error", f"Failed to load Session records: {str(e)}")
async def delete_session(self):
"""删除选中的历史记录"""
try:
# 获取选中项
selected = self.history_tree.selectedItems()
if not selected:
QMessageBox.warning(... | Python | 1 |
usb_dp.set_low();
cortex_m::asm::delay(clocks.sysclk().0 / 100);
let mut led = gpioc.pc13.into_push_pull_output(&mut gpioc.crh);
led.set_high();
let usb_dm = gpioa.pa11;
let usb_dp = usb_dp.into_floating_input(&mut gpioa.crh);
let usb = Peripheral {
... | Rust | 0 |
Relaxed) == 1 {
backoff.snooze();
}
}
}
}
#[must_use]
struct SpinlockGuard {
/// The parent lock.
lock: &'static Spinlock,
}
impl Drop for SpinlockGuard {
#[inline]
fn drop(&mut self) {
self.lock.state.store(0, Ordering::Release);
}
}
// Adapted fro... | Rust | 0 |
"""Print with colors
Python 3.12
Hu Xiangyou
March 24, 2021
May 12, 2021
Oct 22, 2021
June 11, 2024
Part of https://github.com/huxiangyou/hulubot
under MIT License
"""
import ctypes
import builtins
C_WHITE=15
C_SILVER=7
C_GRAY=8
C_BLACK=0
C_RED=12
C_MAROON=4
C_YELLOW=14
C_OLIVE=6
C_LIME=10
C_GREEN=2
C_CYAN=11
C_TE... | Python | 1 |
import sqlite3
database_path = "reconstruct_3d/database.db"
db_conn = sqlite3.connect(database_path)
db_cursor = db_conn.cursor()
db_cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = db_cursor.fetchall()
for table in tables:
print(f"Table: {table[0]}")
db_cursor.execute(f"PRA... | Python | 1 |
eAssignment) -> None:
if (
assignment.role is not None
and assignment.role.prototype == Prototype.OWNER
and assignment.decision == DecisionStatus.APPROVED
and self._count_owners(assignment.data_product_id) <= 1
):
raise HTTPException(
... | Python | 1 |
#🇳🇮🇰🇭🇮🇱
# Add your details here and then deploy by clicking on HEROKU Deploy button
from os import environ
API_ID = int(environ.get("API_ID", "20114039"))
API_HASH = environ.get("API_HASH", "87297b8f3cc8fc9bbce591ad30da5896")
BOT_TOKEN = environ.get("BOT_TOKEN", "7847411487:AAFAucaA1orjqYLkAGM74KmUTOGIxW56... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy, sys
import moveit_commander
from moveit_commander import MoveGroupCommander
from geometry_msgs.msg import Pose
from copy import deepcopy
class MoveItCartesianDemo:
def __init__(self):
# 初始化move_group的API
moveit_commander.roscpp_initial... | Python | 1 |
em = InstrId> + '_ {
self.iids.iter().copied()
}
pub fn is_empty(&self) -> bool {
self.iids.is_empty()
}
/// A well-formed Block is always terminated. This is only useful when
/// building a Block.
pub fn is_terminated(&self, func: &Func<'_>) -> bool {
if let Some(&iid)... | Rust | 0 |
} else {
logln!("{}KB", rom.size() / 1024);
}
logln!("Header info:");
logln!(" name: \"{}\"", rom.name().unwrap());
logln!(" maker code: \"{}\"", rom.maker_code().unwrap());
logln!(" game code: \"{}\"", rom.game_code().unwrap());
logln!(" game version: 1.{:#02}", rom.game_version_byte()... | Rust | 0 |
#!/usr/bin/env python3.11
"""
Quality gate enforcement for CI/CD pipeline.
Usage:
python scripts/quality_gate.py <output_dir>
Enforces minimum thresholds for all PE-grade metrics.
"""
import json
import sys
import pathlib
from typing import Dict, Any
def load_metrics(output_dir: pathlib.Path) -> Dict[str, ... | Python | 1 |
= "Bit 6 - FACCEN"]
#[inline(always)]
pub fn faccen(&mut self) -> FACCEN_W {
FACCEN_W { w: self }
}
#[doc = "Bits 4:5 - MWID"]
#[inline(always)]
pub fn mwid(&mut self) -> MWID_W {
MWID_W { w: self }
}
#[doc = "Bits 2:3 - MTYP"]
#[inline(always)]
pub fn mtyp(&mut ... | Rust | 0 |
ange
_ => self.write_byte(0xfe),
}
}
}
}
impl fmt::Write for Writer {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.write_string(s);
Ok(())
}
}
/// Like the `print!` macro in the standard library, but prints to the VGA text buffer.
#[macro_expor... | Rust | 0 |
similarity = dot / (norm1 * norm2)
self.logger.debug(f"初始相似度计算结果: {similarity}, 类型: {type(similarity)}")
# 确保结果是标量值,而不是数组
if isinstance(similarity, np.ndarray):
self.logger.debug(f"相似度是NumPy数组,形状: {similarity.shape}, 数据类型: {similarity.dtype}, 值: {si... | Python | 1 |
from collections import Counter
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
freq = Counter(nums)
result = [i for i in nums if freq[i]%2!=0]
return result
| Python | 1 |
ut buffer[..1])?;
let packet_size = u8::from_le_bytes(buffer[..1].try_into().unwrap());
if packet_size & 0b10000000 == 0 {
// Raw packet
for _ in 0..=packet_size {
file.read_exact(&mut buffer[..3])?;
... | Rust | 0 |
import os
from src.datascience import logger
import pandas as pd
from src.datascience.entity.config_entity import DataValidationConfig
class DataValidation:
def __init__(self, config: DataValidationConfig):
self.config = config
def validate_all_columns(self) -> bool:
try:
validat... | Python | 1 |
"main entrypoint for exporting an installable python package given a closure"
from pathlib import Path
import shutil
from pylibcollect.export.pkg.link import LinkPatcher
from pylibcollect.export.pkg.out_dir import ExportedLib
from pylibcollect.export.types import DepClosure, InternalLib, LibDep
import logging
logger ... | Python | 1 |
ESP_TEXT","INTERFACE_RESP_BODY","INTERFACE_RESP_CONTENT",
"DUBBO_TEXT"]
varKeyStrip = strTobeProcessed.strip()
if varKeyStrip not in constKeyList:
varValue = "<ERROR:不合法的常量%s,支持常量%s>" % (varKeyStrip, constKeyList)
context.setERROR(varValue)
else:
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.