text string | label_name string | labels int64 |
|---|---|---|
lf,event=None):
tabList = self.parent.selPanel.tabList
def updateTabList(self,event=None):
tabListNames = ['All opened tables']+self.tabList.getDisplayTabNames()
#try:
#iSel=np.min([self.cbTabs.GetSelection(),len(tabListNames)])
#self.cbTabs.Clear()
#[self.cbTabs.App... | Python | 1 |
return len(re.findall(pattern, text, re.IGNORECASE))
def _count_phone_numbers(self, text: str) -> int:
"""Count phone number patterns"""
pattern = r'\b\d{5,}\b|call\s+\d+|\d{4,}-\d{4,}'
return len(re.findall(pattern, text, re.IGNORECASE))
def _count_urls(self, text: str) -> i... | Python | 1 |
cncNcdpPriority,
"cncNcdpStratum": cncNcdpStratum,
"cncNcdpPRSReference": cncNcdpPRSReference,
"cncNcdpSourceHealth": cncNcdpSourceHealth,
"cncNcdpRowStatus": cncNcdpRowStatus,
"cncNcdp": cncNcdp,
"cncNcdpAtmTable": cncNcdpAtmTable,
"cncNcdpAtmEntry": cncNcdpAtmEntry,
... | Python | 1 |
import os
import unittest
import json
from typing import Dict
from jc.parsers.os_release import parse
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
class MyTests(unittest.TestCase):
f_in: Dict = {}
f_json: Dict = {}
@classmethod
def setUpClass(cls):
fixtures = {
'os_relea... | Python | 1 |
"""Block ud.ro.SetSpaceAfter for heuristic setting of SpaceAfter=No in Romanian.
Usage::
udapy -s ud.ro.SetSpaceAfter < in.conllu > fixed.conllu
Author: Martin Popel
"""
import re
import udapi.block.ud.setspaceafter
class SetSpaceAfter(udapi.block.ud.setspaceafter.SetSpaceAfter):
"""Block for heuristic sett... | Python | 1 |
tokio::main]
async fn main() -> Result<(), std::io::Error> {
let opt = Opt::from_args();
pretty_env_logger::init_timed();
let config = Config::from_args(&opt.cert, &opt.key, &opt.sets)?;
let servers: Servers = config.into();
servers.start().await?;
Ok(())
}
<reponame>bast/gotham
// list here all files/... | Rust | 0 |
FunctionCallbackArguments,
mut _rv: v8::ReturnValue|
{
let mut result = String::new();
for idx in 0..(args.length()) {
result.push_str(&args.get(idx).to_rust_string_lossy(scope));
}
println!("{}", result);
})
.build(scop... | Rust | 0 |
type Raw: Copy;
/// The corresponding Snapshot flags
const FLAGS: u32;
/// The `*32First` windows function
const ITER_FIRST: Tl32helpFunc<Self::Raw>;
/// The `*32Next` windows function
const ITER_NEXT: Tl32helpFunc<Self::Raw>;
/// Creates a new instance of this raw representation and i... | Rust | 0 |
1, shift_logit.size(-1)), shift_label.view(-1))
wiki_loss_container.append(wiki_ppl_loss)
wiki_ppl = np.exp(torch.cat(wiki_loss_container, dim=-1).mean().item()).item()
wiki_results = {'wikitest2_perplexity': wiki_ppl}
logger.i... | Python | 1 |
day in DAYS}
for course in selected:
for ts in solution[course.code].time_slots:
schedule[ts.day].append((ts.start_hour, ts.start_minute, course))
for day in DAYS:
lines.append(f"\n{day}:")
lines.append("-" * 40)
entries = sorted(schedule[... | Python | 1 |
});
}
fn respawn_all_players(data: &mut TaskData) {
use crate::server::component::channel::OnPlayerRespawn;
use crate::server::component::event::{PlayerRespawn, PlayerRespawnPrevStatus::*};
use crate::server::component::flag::{IsDead, IsSpectating};
#[derive(SystemData)]
struct RespawnAllData<'a> {
channel: Wr... | Rust | 0 |
from enum import Enum
class NodeType(Enum):
CERT_TEMPLATE = "CertTemplate"
COMPUTER = "Computer"
DOMAIN = "Domain"
ENTERPRISE_CA = "EnterpriseCA"
GROUP = "Group"
GPO = "GPO"
OU = "OU"
ROOT_CA = "RootCA"
USER = "User"
NODE_TYPES = {node_type.name: node_type.value for node_type in ... | Python | 1 |
coder
.encode_iid_symbols_reverse(&symbols, &encoder_codebook)
.unwrap();
assert!(coder.len() > amt);
let reconstructed = coder
.decode_iid_symbols(amt, &decoder_codebook)
.collect::<Result<Vec<_>, _>>()
.unwrap();
assert_eq!... | Rust | 0 |
let cat_fact = State::new(String::new());
let fetch_cat_fact = set_state!(
async || {
let resp = reqwest::get("https://catfact.ninja/fact?max_length=140")
.await
.unwrap();
*(*cat_fact).borrow_mut() = resp.text().await.unwrap();
},
[ca... | Rust | 0 |
problema += (
lpSum(x[ni, nj, b2, o2] for (ni2, nj2, b2, o2) in x if ni2 == ni and nj2 == nj and b2 != b) <= 1 - x[i, j, b, o]
)
elif o == 1 and i + barcos[b] <= n: # Barco vertical
for l in range(barcos[b]):
for di, dj in [... | Python | 1 |
assert_eq!(chainedhashtable.remove(&'a'), Some('a'));
assert_eq!(chainedhashtable.remove(&'b'), Some('b'));
assert_eq!(chainedhashtable.remove(&'c'), Some('c'));
assert_eq!(chainedhashtable.remove(&'d'), Some('d'));
assert_eq!(chainedhashtable.remove(&'e'), Some('e'));
assert_eq!... | Rust | 0 |
BackedValue::try_from_ruby) extracts an `Rc<RefCell<T>>` from an
//! `mrb_value` and manages the strong count of the `Rc` smart pointer to ensure
//! that the `mrb_value` continues to point to valid memory.
//!
//! These `mrb_value`s with type tag `MRB_TT_DATA` can be used to implement Ruby
//! `Class`es and `Modul... | Rust | 0 |
, unused_options_map, config):
'''Iterate again, to flag unmatched entries'''
config_obj = literal_eval(config)
if not config_obj.get('flag_unmatched'):
return (entries, [])
new_entries = []
zs_accounts = config_obj['zerosum_accounts'].keys()
for entry in entries:
if isinstance... | Python | 1 |
idx)
w_idxs = np.arange(self.max_w_idx)
idxs = np.stack(np.meshgrid(h_idxs, w_idxs)).transpose(0, 2, 1).reshape(2, -1).T
n_patches = len(idxs)
while count * batch_size < n_patches:
# Yield a batch of patches
patches = self.get_patches(
idxs[count... | Python | 1 |
class Solution:
def largestIsland(self, grid: List[List[int]]) -> int:
n = len(grid)
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
island_id = 2
island_size = {}
def dfs(i, j, island_id):
""" DFS to mark the island an calculate size """
if i < 0 or i >= ... | Python | 1 |
)?
} else {
hour
};
Ok(TimeSpec::new(hour,min,0))
}
fn am_pm(name: &str, mut hour: u32) -> DateResult<u32> {
if name == "pm" {
hour += 12;
} else
if name != "am" {
return date_result("expected am or pm");
}
Ok(h... | Rust | 0 |
calc_n_partials(f0_hz: T) -> T:
assert f0_hz.ndim == 2
max_f0_hz = tr.max(f0_hz, dim=1, keepdim=True).values
# TODO(cm): check this calculation
n_partials = 12000 / (max_f0_hz * tr.log10(max_f0_hz))
return n_partials
@staticmethod
def calc_osc_arg(
sr: int, f0_hz... | Python | 1 |
Ordering::Less => {
return Err("The records are not sorted in ascending order".into());
}
Ordering::Greater => {
let g = self.group.clone();
self.first_rec = rec.clone();
... | Rust | 0 |
"""JupyterHub version info"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
# version_info updated by running `tbump`
version_info = (5, 4, 0, "", "")
# pep 440 version: no dot before beta/rc, but before .dev
# 0.1.0rc1
# 0.1.0a1
# 0.1.0b1.dev
# 0.1.0.dev
__vers... | Python | 1 |
from openai_harmony import (
load_harmony_encoding,
HarmonyEncodingName,
)
test_gpt_oss = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
print(test_gpt_oss)
| Python | 1 |
break
elif linha['status_code'] == 429:
sleep(60)
continue
elif linha['status_code'] == 403:
raise Exception("Status 403: Atualizar autenticador.")
else:
tabela.append(linha['data'])
... | Python | 1 |
new(1000000.0,3000000.0));
// create basic pm to store outputs
let mut ead_dist = ProductMoments::new();
//create a random number generator for the loop.
let seed = 1234;
let mut randy = StdRng::seed_from_u64(seed);
let iterations = 100;
for i in 0..iterations{
//sample flow frequenc... | Rust | 0 |
ner import (
AlignPropConfig,
AlignPropTrainer,
AllTrueJudge,
BaseBinaryJudge,
BaseJudge,
BasePairwiseJudge,
BaseRankJudge,
BCOConfig,
BCOTrainer,
CPOConfig,
CPOTrainer,
DataCollatorForCompletionOnlyLM,
DPOConfig,
... | Python | 1 |
w
buf = os.read(self.fd, size - len(read))
read.extend(buf)
if ((self._timeout is not None and self._timeout >= 0) or
(self._interCharTimeout is not None and self._interCharTimeout > 0)) and not buf:
break # early abort on timeou... | Python | 1 |
import strawberry
from mock_spotify_rest_api_client.api.playlists import get_featured_playlists
from mock_spotify_rest_api_client.api.playlists import get_playlist
from .types.playlist import Playlist
from .types.track import Track
@strawberry.type
class Query:
@strawberry.field(description="Playlists hand-picked... | Python | 1 |
encoded string.
pub trait ToBase58Check {
/// Converts a value of `self` to a base58 value, returning the owned string.
/// The version is a coin-specific prefix that is added.
/// The suffix is any bytes that we want to add at the end (like the "iscompressed" flag for
/// Secret key encoding)
fn t... | Rust | 0 |
#[inline]
pub fn pose(mut self, value: Posef) -> Self {
self.inner.pose = value;
self
}
#[inline]
pub fn radius(mut self, value: f32) -> Self {
self.inner.radius = value;
self
}
#[inline]
pub fn central_angle(mu... | Rust | 0 |
from .auth import User, Role, RefreshToken
from .character import Character, CharacterPrompt, CharacterImage, UserCharacterImage
from .chat import ChatRoom, ChatMessage
__all__ = [
'User', 'Role', 'RefreshToken',
'Character', 'CharacterPrompt',
'CharacterImage', 'UserCharacterImage',
'ChatRoom', 'ChatM... | Python | 1 |
let mut required_buffers = (size + self.chunk_size - 1) / self.chunk_size;
if required_buffers > self.max_pool_size {
return Err(BufferError::NoAvailableBuffers(format!(
"Message too big for the current BufferConfig {} bytes. \
chunk_size: {}, max_pool_size: {}"... | Rust | 0 |
_part2[1], n_part2[1], drop)
self.mlp2 = Mlp_JpTrans(n_part2[1]*2, n_part2[1], n_part2[1], drop)
self.mlp3 = Mlp_JpTrans(n_part2[1]*2, n_part2[1], n_part2[1], drop, out_act=False)
else:
self.mlp1 = Mlp_JpTrans(n_part2[0], n_part2[1], n_part2[1], drop, out_act=False)
s... | Python | 1 |
current database is "+str(tname))
def ColumnsTime():
n = 200 #预测某个表所有列名称最大可能的长度,根据实际情况填写
k = 0
j = n//2
length = 0
cname = str()
while True:
if j>k and j<n and j-k>3:
payload7 = "lili' and if((length((sele... | Python | 1 |
from ayon_server.settings import BaseSettingsModel, SettingsField
class CreateShotClipModel(BaseSettingsModel):
hierarchy: str = SettingsField(
"shot",
title="Shot parent hierarchy",
section="Shot Hierarchy And Rename Settings"
)
useShotName: bool = SettingsField(
True,
... | Python | 1 |
_pow::StorePowOp {}));
result.push(Box::new(store_sin::StoreSinOp {}));
result.push(Box::new(store_sqrt::StoreSqrtOp {}));
result.push(Box::new(store_sub::StoreSubOp {}));
result.push(Box::new(store_tan::StoreTanOp {}));
result.push(Box::new(val_abs::ValAbsOp {}));
result.push(Box::new(val_add::... | Rust | 0 |
bol == "MLTT" {
return Ok(TokenPrice {
usd_price: Ratio::from_integer(1u32.into()),
last_updated: Utc::now(),
});
}
if let Some(cached_value) = self.get_stored_value(token.id).await {
return Ok(cached_value);
}
let api... | Rust | 0 |
"""The NEW_NAME integration."""
from __future__ import annotations
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from .const import DOMAIN
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
""... | Python | 1 |
# Copyright: Ajatt-Tools and contributors; https://github.com/Ajatt-Tools
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import enum
@enum.unique
class HTMLPitchPatternStyle(enum.Enum):
"""
Styles for HTML pitch patterns.
"""
u_biq = enum.auto()
u_biq_color_coded ... | Python | 1 |
);
}
impl TCOD_font_flags_t {
#[doc = " A unique layout used by some of libtcod's fonts."]
pub const TCOD_FONT_LAYOUT_TCOD: TCOD_font_flags_t = TCOD_font_flags_t(8);
}
impl TCOD_font_flags_t {
#[doc = " Decode a code page 437 tileset into Unicode code-points."]
#[doc = " \\rst"]
#[doc = " .. vers... | Rust | 0 |
to_be_bytes()); //bgpSourceAsNumber 4Byte AS
length += 4;
bytes.put_slice(&(0u32).to_be_bytes()); //bgpDestinationAsNumber 4Byte AS
length += 4;
} else {
bytes.put_slice(&(0u16).to_be_bytes()); //bgpSourceAsNumber 2Byte AS
lengt... | Rust | 0 |
cancel the swap.
// ///
// /// The dispatch origin for this call must be _Signed_.
// ///
// /// - `currency`: Currency of the atomic swap.
// /// - `target`: Receiver of the atomic swap.
// /// - `hashed_proof`: The blake2_256 hash of the secret proof.
// /// - `balance`: Funds to be sent from origin.
/... | Rust | 0 |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
from pathlib import Path
import torch
from mmcls.apis import init_model
from mmcls.models.classifiers import ImageClassifier
def convert_classifier_to_deploy(model, save_path):
print('Converting...')
assert hasattr(model, 'backbone') and \
... | Python | 1 |
from gravar_arquivo import gravar_arquivo
from gravar_arquivo import gravar_arquivo_teclado
from ler_arquivo import ler_arquivo
from ler_arquivo import ler_arquivo_desestruturado
from reconhecimento_voz import ouvir_microfone
def menu():
print("=== Menu de Opções ===")
print("1. Criação e inicialização do arqu... | Python | 1 |
EcdhEs<'_, P256KeyPair>,
P256KeyPair,
AesKey<A256Kw>,
>(
&BOB_SECRET_KEY_AGREEMENT_KEY_P256_2.id,
vec![&BOB_SECRET_KEY_AGREEMENT_KEY_P256_2],
&ALICE_VERIFICATION_METHOD_KEY_AGREEM_P256.id,
&ALICE_VERIFICATION_METHOD_KEY_AGREEM_P256,
... | Rust | 0 |
"XXOX".to_string();
let res = 2;
assert_eq!(Solution::minimum_moves(s), res);
let s = "OOOO".to_string();
let res = 0;
assert_eq!(Solution::minimum_moves(s), res);
}
use crate::renderers::path_tracer::Material;
use crate::textures::color_provider::ColorProvider;
use crate::textures::samplers::line... | Rust | 0 |
n)).is_err());
}
#[test]
fn test_nom_invalid_period_with_range_specifier() {
let expression = "10-12/10-12 * * * * ?";
assert!(schedule(Input(expression)).is_err());
}
#[test]
fn test_nom_valid_days_of_month_any() {
let expression = "* * * ? * *";
schedule(Input... | Rust | 0 |
files in os.walk(newipdir):
print("目录:" + root)
for name in files:
NewFileName = name.replace(" ", '');
NewFileName = os.path.join(root, NewFileName);
os.rename(os.path.join(root, name), os.path.join(root, NewFileName))
... | Python | 1 |
: &str = "...";
/// Does `s` conform to the fuzzy pattern `pattern`? Note that `plines` is expected not to start or
/// end with blank lines, and each line is expected to be `trim`ed.
pub(crate) fn match_vec(plines: &[&str], s: &str) -> bool {
debug_assert!(plines.is_empty() || !plines[0].is_empty());
debug_as... | Rust | 0 |
;
}
// for: classic foreach
let array_two = [10, 20, 30, 40, 50];
for element_two in array_two.iter() {
println!("for array value: {}", element_two);
}
for number_one in (1..4).rev() {
println!("for countdown: {}", number_one);
}
println!("for LIFTOFF");
}
mod parse;
... | Rust | 0 |
# Simulate a sports tournament
import csv
import sys
import random
# Number of simluations to run
N = 10000
def main():
# Ensure correct usage
if len(sys.argv) != 2:
sys.exit("Usage: python tournament.py FILENAME")
teams = []
# TODO: Read teams into memory from file
filename = sys.argv... | Python | 1 |
.header(header::EXPIRES, "Sat, 07 May 2016 15:35:18 GMT"),
),
);
let mismatch = policy.before_request(&request_parts(Request::builder().method(Method::POST).uri("/test")), now);
assert!(matches!(mismatch, http_cache_semantics::BeforeRequest::Stale {matches, ..} if !matches));
}
#[test]
fn requ... | Rust | 0 |
import pytest
from datetime import datetime, timedelta
from timebomb import warn_after, slow_after, fail_after, TimebombError
def small_ms_time_diff(end, start):
return (end - start + 1000000) % 1000000
def test_warn_after_doesnt_warn_before_expired():
res = None
def handle_warn(msg):
nonlocal ... | Python | 1 |
0xb);
// Write the slice content to the created file.
let ret = vibrio::syscalls::Fs::write_at(fd, slice.as_ptr() as u64, 256, 0)
.expect("FileWrite syscall failed");
assert_eq!(ret, 256);
let fileinfo = vibrio::syscalls::Fs::getinfo("file.txt\0".as_ptr() as u64)
... | Rust | 0 |
import asyncio
from loguru import logger
from quantalogic_codeact.cli_commands.config_manager import load_global_config
from quantalogic_codeact.commands.toolbox.uninstall_toolbox_core import uninstall_toolbox_core
async def uninstall_toolbox(shell, args: list[str]) -> str:
"""Uninstall a toolbox and sync Agent... | Python | 1 |
tasks[i] = task
self.save_tasks(tasks)
if record_history:
self.history.record({
"op": "update",
"before": old_task.to_dict(),
"after": task.to_dict()
})
... | Python | 1 |
(split_call):
return "cn" + str(len(split_call) + 2)
if cnvtag == "dup_dup_exon9hyb_star13intron1":
return "cn4"
return "_".join(split_call)
def check_cn_match(sv_list, cn_increase, cn_decrease, final_cn):
"""
Check that the CNV combination produces the right final copy number.
"""... | Python | 1 |
));
linearizes_to!(number_literal_id_optimization, "(=> 5 5)", |i| (
vec![linear::Match {
operation: IntegerValue(LhsId(0)),
expected: Ok(i(5).into()),
}],
vec![MakeIntegerConst {
value: i(5),
bit_width: BitWidth::Polymorphic,
}],
... | Rust | 0 |
jovem = 0
adulta = 0
idosa = 0
s_j = 0
s_a = 0
s_i = 0
for i in range(9):
n = int(input('Digite a sua idade: '))
if n > 0 and n <= 25:
jovem += 1 | Python | 1 |
vally, verify the details of the raised exception
assert str(ex_info.value) == "MarketSubmit_OfferData: Invalid client type, 'TSO' provided. Only 'BSP' is supported."
@responses.activate
def test_put_offers_works(mock_certificate):
"""Test that the put_offer method works as expected."""
# First, create ou... | Python | 1 |
# GENERATED VERSION FILE
# TIME: Sun Jun 22 19:38:55 2025
__version__ = '1.2.0+cc63400'
short_version = '1.2.0'
version_info = (1, 2, 0)
| Python | 1 |
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from sources.DataLoader import Cifar10DataLoader
from sources.utils import relu, softmax, accuracy, cross_entropy_loss
import matplotlib.pyplot as plt
import numpy as np
import random
class TestNeuralNet:
def __ini... | Python | 1 |
monomorphize(&constant.literal),
};
trans_const_value(fx, const_)
}
pub fn force_eval_const<'tcx>(
fx: &FunctionCx<'_, 'tcx, impl Backend>,
const_: &'tcx Const,
) -> &'tcx Const<'tcx> {
match const_.val {
ConstKind::Unevaluated(def_id, ref substs, promoted) => {
let substs = fx... | Rust | 0 |
_InvokeTACommand failed: {:?}", code);
Err(Error::from_raw_error(code))
}
}
}
}
}
impl Drop for Session {
fn drop(&mut self) {
unsafe { raw::TEE_CloseTASession(self.handle) };
}
}
<filename>src/tests.rs<gh_stars>0
#![cfg(test)]
use super::sa... | Rust | 0 |
= language_code
persona_data = create_persona_structure(
args.key,
name=name,
prompt=prompt,
entry_message=entry_message,
characteristics=characteristics,
tone_of_voice=tone_of_voice,
skin_tone=... | Python | 1 |
: u32 = 0u32;
#[doc = "*Required features: 'Win32_Media_KernelStreaming'*"]
pub const KSSTREAM_SYNCHRONOUS: u32 = 4096u32;
#[repr(C)]
#[doc = "*Required features: 'Win32_Media_KernelStreaming'*"]
pub struct KSSTREAM_UVC_METADATA {
pub StartOfFrameTimestamp: KSSTREAM_UVC_METADATATYPE_TIMESTAMP,
pub EndOfFrameTim... | Rust | 0 |
#!/usr/bin/env python3
"""Test Ollama-based communication between instances"""
import requests
import json
import time
# Configuration
LEGION_OLLAMA = "http://localhost:11434"
JETSON_OLLAMA = "http://10.0.0.36:11434"
def query_local_model(prompt, model="phi3:mini"):
"""Query local Ollama model"""
response = ... | Python | 1 |
{
uint32_t a;
void daft(uint32_t) const;
void daft(uint8_t) const;
void daft(std::string) const;
void daft(Fred) const;
void daft(Norma) const;
};
"};
let rs = quote! {
use ffi::ToCppString;
let a = ffi::Bob { a: 12... | Rust | 0 |
_pin!($inst, $pin, 10);
};
($inst:ident, adc, ADC, $pin:ident, IN11) => {
impl_pin!($inst, $pin, 11);
};
($inst:ident, adc, ADC, $pin:ident, IN12) => {
impl_pin!($inst, $pin, 12);
};
($inst:ident, adc, ADC, $pin:ident, IN13) => {
impl_pin!($inst, $pin, 13);
};
($i... | Rust | 0 |
f FCA format is not recognized.
# Column 3: 中文名称
chinese_name = row[2].strip()
# Column 4: CAS号
cas_field = row[3].strip()
if ";" in cas_field:
cas_value = [x.strip() for x in cas_field.split(";") if x.strip()]
... | Python | 1 |
.PushLong, 0x0),
Expr.Equ,
Expr.Return,
),
'loc_2CD1',
)
ChrTurnDirection(0x0102, 0x0101, 400)
ChrTalk(
0x0102,
(
'#0020080147V#010F艾丝蒂尔,\n',
'赶快回亚尔摩村吧。',
TxtCtl.Enter,
TxtCtl.Clear,
'#00200... | Python | 1 |
he tree is N.
//!
//! | Operation | Average case | Worst case |
//! | --- | --- | --- |
//! | [`Push front`][Vector::push_front] | O(1) | O(H) |
//! | [`Push back`][Vector::push_back] | O(1) | O(H) |
//! | [`Pop front`][Vector::pop_front] | O(1) | O(H) |
//! | [`Pop back`][Vector::pop_back] | O(1) | O(H) |
//! | [`Slic... | Rust | 0 |
if Y_UP_DISPLAY:
# Slight tweak of viewing angle so Y (up) reads naturally
ax.view_init(elev=20, azim=45)
print("Displaying plot. Close the plot window to exit.")
plt.show()
except Exception as e:
print(f"An error occurred: {e}")
def main():
"""Main function ... | Python | 1 |
(Pr::new("Y", vec![Symbol::n("Y"), Symbol::n("Z")]))
/// .add_pr(Pr::new("Y", vec![Symbol::n("Y"), Symbol::t("a", vec![0])]))
/// .add_pr(Pr::new("Y", vec![Symbol::t("b", vec![0])]))
/// .add_pr(Pr::new("U", vec![Symbol::n("V")]))
/// .add_pr(Pr::new("X", vec![Symbol::t("c", vec![0])]))
/// .add_pr(... | Rust | 0 |
}
pub fn set_event_destination(
mut self,
input: std::option::Option<crate::model::EventDestinationDefinition>,
) -> Self {
self.inner = self.inner.set_event_destination(input);
self
}
}
}
impl<C> Client<C, aws_hyper::AwsMiddleware, smithy... | Rust | 0 |
ject"),
}
}
fn import_map(
doc: &mut am::AutoCommit,
obj: &am::ObjId,
map: &serde_json::Map<String, serde_json::Value>,
) -> anyhow::Result<()> {
for (key, value) in map {
match value {
serde_json::Value::Null => {
doc.put(obj, key, ())?;
}
... | Rust | 0 |
IMARY KEY, data box)",);
let create_primary = format!("CREATE INDEX \"A_data_idx\" ON \"{schema_name}\".\"A\" USING SPGIST (data);",);
api.database().raw_cmd(&create_table).await?;
api.database().raw_cmd(&create_primary).await?;
let expected = expect![[r#"
model A {
id Int ... | Rust | 0 |
# Define the initial state of the stacks
stacks = [['Green', 'Yellow', 'Red', 'Yellow'], [], ['Blue', 'Blue', 'Blue', 'Red'], [], ['Green', 'Green', 'Red', 'Yellow'], []]
# Define the cost of moving one block to the top of each stack
cost = {0: 3, 1: 6, 2: 5, 3: 5, 4: 3, 5: 1}
# Initialize a list to store the transf... | Python | 1 |
class TaskFamily:
@staticmethod
def get_tasks() -> dict[str, dict]:
return {
"1": {"problem": "Sort a list of integers using a custom sorting rule.", "constraints": "The sorting rule should prioritize even numbers over odd numbers and within each parity, numbers should be sorted in ascending... | Python | 1 |
T: PrimInt + Signed + Display, const N: u32> Display for DecimalFixedPoint<T, N> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}{}.{:0>precision$}",
self.0.is_negative().then(|| "-").unwrap_or(""),
(self.0 / Self::exponent... | Rust | 0 |
to_vec(), 2),
)
.unwrap();
rx.recv().unwrap();
storage
.async_get(
Context::new(),
make_key(b"y"),
101,
expect_get_val(tx.clone(), b"100".to_vec(), 3),
)
.unwrap();
rx.recv... | Rust | 0 |
pub unsafe extern "C" fn opj_j2k_destroy(mut p_j2k: *mut opj_j2k_t) {
if p_j2k.is_null() {
return;
}
if (*p_j2k).m_is_decoder != 0 {
if !(*p_j2k).m_specific_param.m_decoder.m_default_tcp.is_null() {
opj_j2k_tcp_destroy((*p_j2k).m_specific_param.m_decoder.m_default_tcp);
opj_free((*p_j2k).m_sp... | Rust | 0 |
vation_record(record.index, record.wallet_id, record.hardened) == record
assert await db.get_wallet_identifier_for_puzzle_hash(record.puzzle_hash) == WalletIdentifier(
record.wallet_id, record.wallet_type
)
# Remove one wallet after the other and verify before... | Python | 1 |
def help_main(Env):
Mod = Env.Current
Orig = Mod.Module
Mod.Module = 'dual_'+Mod.Module
Mod.alwayses = []
Mod.generates = []
Mod.insts = {}
Mod.hard_assigns = []
Nets = list(Mod.nets.keys())
for Net in Nets:
Dir,Wid = Mod.nets[Net]
if internalDir(Dir):
... | Python | 1 |
.unwrap(), ""),
Err(_) => assert!(false),
}
merger.skip_head(Skip::Lines(4));
buf.clear();
match merger.merge_sources_into(vec![&mut c1, &mut c2, &mut c3], &mut buf) {
Ok(_) => assert!(false),
Err(e) => match e {
ErrorKind::InvalidSkip => assert!(true),
_... | Rust | 0 |
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import TensorDataset, DataLoader
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import accuracy_score, classification_repo... | Python | 1 |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <div style="text-align:center;">
# <h1 style="fo... | Python | 1 |
import socket
import time
import telnetlib
import struct
import sys
# from https://github.com/niklasb/ctf-tools/tree/master/pwnlib
import pwnlib.tools as t
#TARGET=('localhost', 9797)
TARGET=('semanager.asis-ctf.ir', 9797)
s=None
def connect():
global s
if s is not None:
s.close()
s=socket.create_... | Python | 1 |
able));
}
// The rest of the system's RAM
// PERF: Map the rest of the RAM lazily?
for region in MEMORY_MAP.present_regions().filter(|reg| reg.region_type == RegionType::Ram) {
// If a region doesn't start or end at a page boundary, we'll treat that part as uncacheable.
// Everything el... | Rust | 0 |
import numpy as np
import pandas as pd
def evaluate(prediction, ground_truth, mask, report=False):
assert ground_truth.shape == prediction.shape, 'shape mis-match' # 断言:真实值和预测值的形状必须匹配
performance = {} # 初始化性能字典
# mse (Mean Squared Error, 均方误差)
performance['mse'] = np.linalg.norm((prediction - ground_t... | Python | 1 |
n(sd: &mut spc_pdf_) -> Result<()> {
if !sd.annot_dict.is_null() {
warn!("Unbalanced bann and eann found.");
pdf_release_obj(sd.annot_dict);
}
sd.lowest_level = 255;
sd.annot_dict = ptr::null_mut();
sd.resourcemap.clear();
pdf_release_obj(sd.cd.taintkeys);
sd.cd.taintkeys = p... | Rust | 0 |
{
"kicad" => KicadNetListSerializer::new().serialize(&circuit),
"dot" => DotSerializer::new().serialize(&circuit),
_ => unreachable!(),
};
let output = match output_result {
Ok(out) => out,
Err(err) => {
println!("Failed to serialize: {}", err);
p... | Rust | 0 |
dge_low(&self) -> GPIO20_EDGE_LOW_R {
GPIO20_EDGE_LOW_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 17"]
#[inline(always)]
pub fn gpio20_level_high(&self) -> GPIO20_LEVEL_HIGH_R {
GPIO20_LEVEL_HIGH_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 16"]
#[inline(... | Rust | 0 |
nfig.smtp().port(),
)
# Send message
refused_recipients = smtp.sendmail(mime_message['From'], mime_message['To'], mime_message.as_string())
if len(refused_recipients):
log.warning("Unable to send email to the following recipients: %s" % str(refused_recipi... | Python | 1 |
error_if_server_does_not_use_ed25519_cert() {
let (client_cert, client_private_key) = generate_tls_keys(COMMON_NAME, NOT_AFTER);
let server = CustomServer::builder()
.with_allowed_signature_algorithms("ECDSA+SHA256:RSA+SHA256:ed25519")
.expect_error("no suitable signature algorithm")
.bu... | Rust | 0 |
payable_uuid.as_bytes(), &payable_meta)?;
Ok(Response::new()
.add_messages(messages)
.add_attributes(attributes))
}
/// A helper struct that contains all output relevant to charging a fee for registration.
struct FeeChargeResponse {
fee_charge_message: Option<CosmosMsg<ProvenanceMsg>>,
fee_... | Rust | 0 |
import time
import numpy as np # type: ignore
def print_time(start_time, T, t_max, episode, episode_rewards):
"""
打印当前训练进度的时间信息
参数:
start_time (float): 训练开始的时间戳(由 time.time() 得到)
T (int): 当前已进行的时间步数(或当前回合的步数)
t_max (int): 训练的最大时间步数
episode (int): 当前回合的编号
episode_rew... | Python | 1 |
#!/usr/bin/env python3
# Copyright 2019, VIXL authors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this lis... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.