text
string
label_name
string
labels
int64
# quantum_state/density_matrix.py import numpy as np class DensityMatrix: """Class representing a quantum state using a density matrix.""" def __init__(self, matrix): """Initializes the density matrix with the given matrix. Args: matrix (list or np.ndarray): The densi...
Python
1
Absolute path to the test target pub file: &'static str, /// The line number at which the test target is defined pub line: u32, /// The path to the current test pub item_path: &'static str, /// The name of the test pub test_name: Option<String>, } impl TargetLocation { pub fn should...
Rust
0
import re from .common import InfoExtractor from ..utils import ExtractorError class NewsPicksIE(InfoExtractor): _VALID_URL = r'https://newspicks\.com/movie-series/(?P<channel_id>\d+)\?movieId=(?P<id>\d+)' _TESTS = [{ 'url': 'https://newspicks.com/movie-series/11?movieId=1813', 'info_dict': ...
Python
1
String, } #[derive(Debug)] enum UnhandledError { Transport(reqwest::Error), Api { code: i32, message: String }, } impl From<reqwest::Error> for UnhandledError { fn from(err: reqwest::Error) -> UnhandledError { UnhandledError::Transport(err) } } <filename>gio/src/auto/emblem.rs // This file wa...
Rust
0
.max() .unwrap(); // rightup let rightup_ans = iproduct!(3..height, 0..width - 3) .map(|(i, j)| list[i][j] * list[i - 1][j + 1] * list[i - 2][j + 2] * list[i - 3][j + 3]) .max() .unwrap(); let ans = [updown_ans, leftright_ans, rightdown_ans, rightup_ans] .iter() .max() .unwrap() .to_owned(); pri...
Rust
0
, &validator_signer); let a1_output = a1 .accumulator_extension_proof() .verify( a1.block() .quorum_cert() .certified_block() .executed_state_id(), ) .unwrap(); let evil_proof = Proof::new( a1_output.frozen_sub...
Rust
0
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from typing import Type class Adapter(nn.Module): def __init__(self, D_features, ...
Python
1
not create region for \"{}\"", region))?; debug!("Loaded region is {}", r); let c = Credentials::new(None, None, None, None, profile) .with_context(|| format!( "Could not load S3 credentials for profile \"{}\"", profile.unwrap_or("default"), ))?; // C...
Rust
0
manager, None); let placeholder = self.placeholder.clone(); let placeholder_style = self.placeholder_style.clone(); use_layout_effect!(manager, move |link, buffer| { let id = match view_ref.apply(link, |&mut id| id) { Some(id) => id, None => return, ...
Rust
0
import zipfile, os import shutil from typing import List, Tuple SUPPORTED_LANGUAGES = { '.py': 'python', '.java': 'java', '.js': 'javascript', '.xml': 'xml', '.json': 'json', '.yml': 'yaml', '.yaml': 'yaml', '.sql': 'sql' } class FileExtractor: def __init__(self, zip_path: str, ext...
Python
1
async fn update_batch_by_id<T>(&self, context_id: &str, args: &[T]) -> Result<u64> where T: CRUDEnable { let mut updates = 0; for x in args { updates += self.update_by_id(context_id, x).await? } Ok(updates) } async fn fetch_by_wrapper<T>(&self, context_id: &str, ...
Rust
0
import docx.text.paragraph from docx import Document from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.oxml.ns import qn from docx.shared import RGBColor, Pt class DocxGenerator: def __init__(self): self.__doc_handle = Document() self.__generate_path = None def set_path(self, path: str)...
Python
1
def get_context(context): # do your magic here context.show_sidebar = True
Python
1
""" 该文件将脚本里创建的 alg, sampler, buffer, evaluator 这4个对象整合在一起 实现算法的整体【训练+评估】的流程 """ _all__ = ["OffSerialTrainer"] from cmath import inf import os import time import torch from torch.utils.tensorboard import SummaryWriter from Multi_RL.utils.tensorboard_setup import tb_tags, add_scalars from Multi_RL.utils.log_data impo...
Python
1
from test import test_support import unittest nis = test_support.import_module('nis') class NisTests(unittest.TestCase): def test_maps(self): try: maps = nis.maps() except nis.error, msg: # NIS is probably not active, so this test isn't useful self.skipTest(str(...
Python
1
_EXTERNAL_BOOTLIN=y BR2_PACKAGE_HOST_GDB=y BR2_GDB_VERSION_11=y BR2_PACKAGE_GDB=y BR2_PACKAGE_GDB_DEBUGGER=y BR2_TARGET_ROOTFS_CPIO=y # BR2_TARGET_ROOTFS_TAR is not set """ def test_run(self): self.verify_host_gdb() self.boot() self.ve...
Python
1
#!/usr/bin/env python """Test functions for fftpack.helper module Copied from fftpack.helper by Pearu Peterson, October 2005 """ from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import TestCase, run_module_suite, assert_array_almost_equal from numpy import fft fr...
Python
1
s[18] = ((s6 >> 18) | (s7 << 3)) as u8; s[19] = (s7 >> 5) as u8; s[20] = (s7 >> 13) as u8; s[21] = (s8 >> 0) as u8; s[22] = (s8 >> 8) as u8; s[23] = ((s8 >> 16) | (s9 << 5)) as u8; s[24] = (s9 >> 3) as u8; s[25] = (s9 >> 11) as u8; s[26] = ((s9 >> 19) | (s10 << 2)) as u8; s[27] = ...
Rust
0
}, MapPos{v: Vector2{x: 3, y: 3}}, MapPos{v: Vector2{x: 3, y: 4}}, MapPos{v: Vector2{x: 3, y: 5}}, MapPos{v: Vector2{x: 3, y: 6}}, MapPos{v: Vector2{x: 4, y: 6}}, MapPos{v: Vector2{x: 5, y: 7}}, MapPos{v: Vector2{x: 5, y: 8}}, MapPos{v: Vector2{x: 6, y: 9}...
Rust
0
# Binary Analysis Next Generation (BANG!) # # This file is part of BANG. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versio...
Python
1
.and(with_admin_session(context)) .and_then(handlers::create) } pub fn delete( context: Context, ) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone { warp::path::param() .and(warp::path::end()) .and(warp::delete()) ...
Rust
0
''' 주민등록번호 뒷자리의 맨 첫 번째 숫자는 성별을 나타낸다. 주민등록번호에서 성별을 나타내는 숫자를 출력해보자. ''' pin = '881120-1068234' print(pin[7]) # 1
Python
1
path.getmtime(file_path)).strftime( "%Y-%m-%dT%H:%M:%S.%fZ" ) # Format parameters string nicely parameters_str = parameter_size if parameters_str == "Unknown" and parameter_count: if parameter_count >= 1_000_000_000: parameters_str = f"{parameter_count / 1_000_000_000:.1f}B"...
Python
1
count, bucket = ?self.bucket, key = ?metadata.key ); let content_type = HeaderValue::from_str(StandardEncodings::Ndjson.content_type()).unwrap(); let content_encoding = DEFAULT_COMPRESSION .content_encoding() .map(|ce| HeaderValue::from_str(&to_st...
Rust
0
IdentCont = IdentStart | {'0'..='9'}; NotIdent = { {!'a'..='z'} {!'A'..='Z'} {!"_"} {!'0'..='9'} }; Ident = { IdentStart {IdentCont*} NotIdent }; StrLit = { "\"" {{ { {!"\\"} {!"\""} .. } | { "\\" Escape } }*} "\"" }; CharLit = { "'" { { {!"\\"} {!"'"} .. } | { "\\" Escape } } "...
Rust
0
4, 244, 255], # 9 - Definitely Cloud [195, 231, 240, 255], # 10 - Thin Cloud [222, 157, 204, 255], # 11 - Snow or Ice ], dtype="uint8", ) # fmt: on # Load SCL band, then convert to RGB using color scheme above scl_rgba = colorize(xx.SCL.compute(), scl_colormap) # Check we still have geo-re...
Python
1
ER_CLUSTER * args.lists, chunks ) train = np.array( np.memmap( "index.mmap", dtype=np.float32, mode="r", shape=(MAX_POINTS_PER_CLUSTER * k, dim), ) ) else: train = data[:] if metric == "cos": ...
Python
1
site = &state.site; let dir = &state.dir; let scope = &state.scope; let n: String = req.match_info().get(scope).unwrap().parse().unwrap(); let name = &bound(&n); if !Regex::new(r"^[0-9A-Za-z_-]+$").unwrap().is_match(name) || !page_exists(dir, name) { return respond_error(404, site, name, "page not...
Rust
0
WHEN v.major > highest.major THEN v WHEN v.major = highest.major AND v.minor > highest.minor THEN v ELSE highest END ) as latest_version WHERE latest_version IS NOT NULL // 7. Return the appropriate version of each subgroup ...
Python
1
scoreboard players set {carry} 1")); code.push(format!("execute if score {lhs_lo} matches ..-1 if score {rhs_lo} matches 0.. if score {dst_lo} matches 0.. run scoreboard players set {carry} 1")); code.push(format!("execute if score {lhs_lo} matches 0.. if score {rhs_lo} matches ..-1 if score {dst_lo} matches 0.. run...
Rust
0
ew(0); unsafe fn unlock(register_offset: u32) { (*PM).unlock.set(0xAA000000 | register_offset); } unsafe fn select_main_clock(clock: MainClock) { unlock(0); (*PM).mcctrl.set(clock as u32); } /// Enable HCACHE unsafe fn enable_cache() { enable_clock(Clock::HSB(HSBClock::FLASHCALWP)); enable_clock(...
Rust
0
from utils.uitools import FrameWrapper from PyQt5.QtWidgets import ( QFrame, QVBoxLayout, QTableWidgetItem, QPushButton, QSizePolicy, QHeaderView, QLabel, ) from extern import webDict from PyQt5.QtCore import Qt from qfluentwidgets import TableWidget, PushButton, TeachingTip, BodyLabel, Tea...
Python
1
R:aUSSUlX lgg)YUpdate the incumbent if the node set C has greater weight. C is assumed to be a clique. Nrr)rCC_weights r#update_incumbent_if_improved,MaxWeightClique.update_incumbent_if_improved' ++ +#$Q4D $, ! ,rEc...
Python
1
r corner of the bandpass :param bool zerophase: Whether to run the filter forwards and backwards in order to counteract the phase shift :param bool verbose: Verbose, defaults to False :rtype: :py:class:`numpy.ndarray` """ if verbose: fx.printmsg('vertical triangular FIR bandpass filter') ...
Python
1
user_name: Some(user_name), user_agent: self.user_agent, activity_id: self.activity_id, consistency_level: self.consistency_level, } } } impl<'a, 'b, C, D, UserNameSet> UserAgentSupport<'b> for ReplaceUserBuilder<'a, 'b, C, D, UserNameSet> where UserNameS...
Rust
0
target: self.target.variable(), weight: self.weight.as_ub_add(), } } else { debug_assert!(self.target.is_lb()); Edge { source: self.target.variable(), target: self.source.variable(), weight: -sel...
Rust
0
_file = EmbeddingFile::from_reader(file).unwrap(); let header = embedding_file.header(); let num_timesteps = header.num_timesteps; let vocab_size = header.vocab_size; let embedding_dim = header.embedding_dim; dbg!(num_timesteps, vocab_size, embedding_dim); let decompress_t = |t: u32| { ...
Rust
0
Passing Interface bindings for Rust //! //! The [Message Passing Interface][MPI] (MPI) is a specification for a //! message-passing style concurrency library. Implementations of MPI are often used to structure //! parallel computation on High Performance Computing systems. The MPI specification describes //! bindings f...
Rust
0
0); /// ``` pub trait AsLsb0 { fn as_lsb0(&self, n: BitCount) -> Self; } macro_rules! impl_as_lsb0 { ($t: ty, $sz:literal) => { impl AsLsb0 for $t { fn as_lsb0(&self, n: BitCount) -> Self { debug_assert!(n <= $sz); match n { 0 => return *s...
Rust
0
# Copyright (c) 2024, Shanghai Iluvatar CoreX Semiconductor Co., Ltd. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/license...
Python
1
in d: o.charging_end_time = d['charging_end_time'] if 'charging_start_time' in d: o.charging_start_time = d['charging_start_time'] if 'connector_id' in d: o.connector_id = d['connector_id'] if 'elec_amount' in d: o.elec_amount = d['elec_amount'] ...
Python
1
General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. //! Implementation of the `sign` subcommand use crate::{error, utils, with_crypto_scheme, CryptoSchemeFlag, KeystoreParams}; use sp_co...
Rust
0
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th...
Python
1
ciInfo, ManyError>; /// Called at the end of a block. fn end_block(&mut self) -> Result<(), ManyError> { Ok(()) } /// Called after a block. The app should take this call and serialize its state. fn commit(&mut self) -> Result<AbciCommitInfo, ManyError>; } <reponame>azasypkin/kroneum<gh_sta...
Rust
0
client: os::Client::new(), } } pub fn on(&self) -> Result<(), String> { self.toggle(Status::On) } pub fn off(&self) -> Result<(), String> { self.toggle(Status::Off) } pub fn toggle(&self, status: Status) -> Result<(), String> { match self.client.set_enabled(sta...
Rust
0
; } let lookup = TypeLookup::from_types(types); Ok(lookup) } <filename>src/codegen/math/float/sqrt.rs //! Vertical floating-point `sqrt` #![allow(unused)] // FIXME 64-bit 1 elem vectors sqrt use crate::*; pub(crate) trait Sqrt { fn sqrt(self) -> Self; } #[allow(improper_ctypes)] extern "C" { #[link_n...
Rust
0
from __future__ import print_function # -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # -------------------------------------------------------- import numpy as n...
Python
1
ox id (32-byte digest) #[derive(PartialEq, Eq, Debug, Clone)] pub struct BoxId(pub chain::ergo_box::BoxId); pub type BoxIdPtr = *mut BoxId; pub type ConstBoxIdPtr = *const BoxId; /// Parse box id (32 byte digest) from base16-encoded string pub unsafe fn box_id_from_str(box_id_str: &str, box_id_out: *mut BoxIdPtr) -> R...
Rust
0
from types import FunctionType from uuid import UUID from Script.Core import get_text, game_type, cache_control, constant, flow_handle from Script.UI.Moudle import panel, draw from Script.Design import cooking, update, attr_calculation, handle_premise from Script.Config import normal_config, game_config from Script.UI....
Python
1
# SPDX-FileCopyrightText: Copyright (c) 2024-2025, NVIDIA CORPORATION & AFFILIATES. # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import pytest import polars as pl import pylibcudf as plc from cudf_polars.containers import Column, DataType from cudf_polars.dsl.ir import broadcast @pyte...
Python
1
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/gui/impl/lobby/universal_web_event_window/universal_web_event_view.py from gui.impl.gen import R from gui.impl.lobby.common.browser_view import BrowserView from gui.impl.pub.lobby_window import LobbyWindow from helpers import depend...
Python
1
x[i] = x[i] + (k1[i] + 2*(k2[i] + k3[i]) + k4[i]) * CTRL.one_over_six def angle_diff(a,b): # ''' a and b must be within [0, 2*np.pi]''' _, a = divmod(a, 2*np.pi) _, b = divmod(b, 2*np.pi) d1 = a-b if d1 > 0: d2 = a - (b + 2*np.pi) # d2 is negative else: d2 = (2*np.pi + a) ...
Python
1
, ShiftType::Row, ); shift_expression(expr, &shift_context); } pub fn shift_expression_row_on_delete( expr: &mut Expression, expr_row: isize, start_row_index: isize, rows: isize, ) { let shift_context = ShiftContext::new( expr_row, start_row_index, rows, ...
Rust
0
} #[derive(Clone, Debug)] pub enum Op<$lifetime> {$( $name $(($($def)+))* ),+} } } optable! { Lifetime = 'a, // control flow Unreachable = 0x00, Nop = 0x01, Block(InlineSignatureType) = 0x02, Loop(InlineSignatureType) = 0x03, If(InlineSignatureType...
Rust
0
arr = [ [0,0,0], [0,0,0], [0,0,0] ] index = 0 rowIndex = 0 columnIndex = 0 while index < len(arr): arr[rowIndex][columnIndex] = 1 rowIndex += 1 columnIndex += 1 index += 1 for row in arr: print(row)
Python
1
(Copy, Clone)] pub struct GtkRadioActionClass { pub parent_class: GtkToggleActionClass, pub changed: Option<unsafe extern "C" fn(*mut GtkRadioAction, *mut GtkRadioAction)>, pub _gtk_reserved1: Option<unsafe extern "C" fn()>, pub _gtk_reserved2: Option<unsafe extern "C" fn()>, pub _gtk_reserved3: Opt...
Rust
0
000; SameSite=Strict", ); assert_eq!( Cookie::new("name1", value1()).with_secure(true).to_string(), "name1=value1; HttpOnly; Max-Age=2592000; SameSite=Strict; Secure", ); } <filename>tests/test.rs extern crate ipconfig; #[test] fn no_error() { println!("Adapters: {:#?}", ipconfig::get_...
Rust
0
# Any copyright is dedicated to the Public Domain. # http://creativecommons.org/publicdomain/zero/1.0/ #:: IgnoreFile(silicon)(320) from nagini_contracts.contracts import * from nagini_contracts.thread import Thread, getARP, Joinable, getMethod, getArg, ThreadPost from nagini_contracts.obligations import MustTermina...
Python
1
(), "12".to_owned()])); drop(data_manager.save_to("table_name", vec!["1".to_owned(), "2".to_owned(), "3".to_owned()])); drop(data_manager.save_to("table_name", vec!["7".to_owned(), "8".to_owned(), "9".to_owned()])); expect!(data_manager.get_range_till_end_for_column("table_name", 0, 1)) .to(be_equa...
Rust
0
# ----------------------------------------------------------------------------- # From Numpy to Python # Copyright (2017) Nicolas P. Rougier - BSD license # More information at https://github.com/rougier/numpy-book # ----------------------------------------------------------------------------- import numpy as np impor...
Python
1
for i in range(len(o.keys)): a.append(("Key", [o.keys[i]])) a.append(("Value", [o.values[i]])) if o.rest is not None: a.append(("Rest", [o.rest])) return self.dump(a, o) def visit_class_pattern(self, o: mypy.patterns.ClassPattern) -> str: a: list[...
Python
1
import os import json import shutil import glob import copy cnt = 0 for software in ['vs_code', 'libreoffice_impress', 'libreoffice_writer']: res_chat = [] for idx in os.listdir(f'results_en_phase0_multi_init/pred_corr_{software}'): for index in os.listdir(f'results_en_phase0_multi_init/pred_corr_{soft...
Python
1
# Chap01/demo_sklearn.py from sklearn import datasets from sklearn.cluster import KMeans import matplotlib.pyplot as plt if __name__ == '__main__': # Load the data iris = datasets.load_iris() X = iris.data petal_length = X[:, 2] petal_width = X[:, 3] true_labels = iris.target # Apply KMeans...
Python
1
#[derive(Clone, Copy, Debug)] struct Edge { start: m::Vec2, dir: Unit<m::Vec2>, length: f64, } #[derive(Clone, Copy, Debug)] enum EdgeClipResult { /// If edges intersect, we don't care about anything else /// as this means a single contact point at an already known location Intersects, //...
Rust
0
"""SCons.Tool.lex Tool-specific initialization for lex. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is hereby granted, free of charge, to...
Python
1
SVRow", schema_prefix); schema_builder.add_string_triple(StringTriple::new_node( &row_predicate, &rdf_type, &object_property, ))?; schema_builder.add_string_triple(StringTriple::new_value( &row_predicate, &label, &row_predicate_label, ))?; schema_buil...
Rust
0
::new(); scope .compile_and_return(schema, false) .expect("Valid schema"); }, ) }, ); }, validate, validate, ) } fn validate(c:...
Rust
0
[test] fn test_mul1() { let a = BigReal::new(25, 0); let b = BigReal::new(4, 0); let c = a * b; assert_eq!(c, BigReal::new(100, 0)); } #[test] fn test_mul2() { let a = BigReal::new(25, 1); let b = BigReal::new(4, 2); let c = a * b; assert_eq!(c, BigReal::new(100, 3)); } #[test] fn test...
Rust
0
) } struct OutboxHandler(Arc<service::OutboxService>); #[async_trait] impl EventHandler for OutboxHandler { type Event = Event; type Error = anyhow::Error; async fn handle(&self, event: &Self::Event) -> Result<(), anyhow::Error> { log::debug!("Outbox event: {:?}", event); self.0.mark_seen...
Rust
0
output()?; let (output, output_path) = file_and_path(&out_path, &cli.name()?, cli.overwrites())?; let mut encoder = GifEncoder::new_with_speed(&output, 30); encoder.set_repeat(image::codecs::gif::Repeat::Infinite)?; encoder.encode_frames(frames)?; let outputname = &output_path .file_name() ...
Rust
0
# coding: utf-8 """ FinFeedAPI Stock REST API No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: v1 Contact: support@apibricks.io Generated by OpenAPI Generator (https://openapi-generator.tech) Do no...
Python
1
data.borrow_mut().push(byte); } /// Remove the last byte from the current chunk's data. pub fn pop_byte(&mut self) { self.data.borrow_mut().pop(); } /// Get the last byte from the current chunk's data. pub fn get_last_byte(&self) -> u8 { return *self.data.borrow().last().unwrap...
Rust
0
media: &Media) -> Result<(), rusqlite::Error> { let conn = &mut get_conn(data.clone()); let txn = conn.transaction().unwrap(); { let update_thumbnail_stmt = &mut txn .prepare_cached( "UPDATE media SET thumbnail = :thumbnail \ WHERE feed_id = :feed_id AND ...
Rust
0
nager, test_session): """測試獲取分片統計""" # 創建測試分片 shard1 = DataShard( table_name="market_daily", shard_key="date", shard_id="shard_1", start_date=date(2024, 1, 1), end_date=date(2024, 1, 31), row_count=1000, file_siz...
Python
1
.downcast_ref::<fn(&Self, From) -> To>() .map(|f| Box::new(move |x: From| f(self, x)) as Box<dyn Fn(From) -> To>) }) } fn get_as<From, To>(&self, name: &str) -> Option<Box<dyn Fn(From) -> To + '_>> where From: Sized + Any, To: Sized + Any, { let type_ids ...
Rust
0
(master_doc, 'udsoncan', u'udsoncan Documentation', author, 'udsoncan', 'Python implementation of UDS standard (ISO-14229).', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to ...
Python
1
_from_ymd(y1, m1, d1); let expect = date_from_ymd(y2, m2, d2); let found = date_add(date, amount, part).unwrap().unwrap(); assert_eq!( expect, found, "date_add('{}', {}, {:?})", date, amount, part ); if part != DatePart::Month { let...
Rust
0
#[serde(borrow)] metadata: Vec<Metadata<'a>>, } #[derive(Deserialize, Debug, PartialEq)] struct Metadata<'a> { key: &'a str, #[serde(borrow)] value: MetadataValue<'a>, } #[derive(Deserialize, Debug, PartialEq)] struct MetadataValue<'a> { name: &'a str, } #[derive(Serialize, Debug, Default)] stru...
Rust
0
12: &[u8] = include_bytes!("../../resources/1.12.chunk"); const CHUNK_1_17_0: &[u8] = include_bytes!("../../resources/1.17.0.chunk"); const CHUNK_1_17_1: &[u8] = include_bytes!("../../resources/1.17.1.chunk"); const CHUNK_21W44A_1: &[u8] = include_bytes!("../../resources/21w44a-test1.nbt"); const CHUNK_CUSTOM_HEIGHTS_1...
Rust
0
pub fn bits(&self) -> u8 { match *self { WDTSSELR::WDTSSEL_0 => 0, WDTSSELR::WDTSSEL_1 => 1, WDTSSELR::WDTSSEL_2 => 2, WDTSSELR::WDTSSEL_3 => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> WDTSSEL...
Rust
0
yType(4,"goblin","goblin.svg") createEnemyType.save() createEnemyType = EnemyType(5,"dragon","dragon.svg") createEnemyType.save() createEnemyType = EnemyType(6,"orc","orc.svg") createEnemyType.save() createEnemyType = EnemyType(7,"dwarf","dwarf.svg") createEnemyType.save() createEnemyTyp...
Python
1
Load configuration. local_dir = os.path.dirname(__file__) config_path = os.path.join(local_dir, 'test_configuration') config = ctneat.Config(ctneat.DefaultGenome, ctneat.DefaultReproduction, ctneat.DefaultSpeciesSet, ctneat.DefaultStagnation, config_path) ...
Python
1
let storage = MemoryStorage::default(); let mut glue = Glue::new(storage); let _ = glue.execute("CREATE TABLE Test (id INTEGER, name TEXT, phone TEXT)"); let raw_data = std::fs::read_to_string("data.json").unwrap(); let vals: Vec<Person> = from_str(&raw_data).unwrap(); for (idx, val) in va...
Rust
0
class Solution: def destCity(self, paths: List[List[str]]) -> str: count = collections.Counter() for a, b in paths: count[a] += 1 for a, b in paths: if b in count: count[b] -= 1 if count[b] == 0: del count[b] else: return b
Python
1
"_val": metric.avg, name+"_train":states['train'].avg}, step=epoch*self.train_length) new_best_train, new_best_val = self.tracker.update_and_plot(name, epoch, self.checkpoint_path+f"{name}_{self.args.name+self.args.notes}.png") if new_best_val: other_tools...
Python
1
}, &[" lab:", " bsr.s lab"], ); } // lab: // bsr.w lab #[test] fn test_decode_0211_lab_() { test_decoding_result_ok( &[0x61, 0x00, 0xff, 0xfe], Instruction { size: 2, operation: BSR, ...
Rust
0
set = ncx .node_builder(Lir::Add) .operand(base.val_out(0)) .operand(offset.val_out(0)) .finish(); ncx.node_builder(Lir::Load) .operand(base_offset.val_out(0)) .state(state_port) ...
Rust
0
import pytest from torch import nn from e2e_sae.models.mlp import MLP, Layer @pytest.mark.parametrize( "hidden_sizes, bias, expected_layer_sizes", [ # 2 hidden layers, bias False ([4, 3], False, [(3, 4), (4, 3), (3, 4)]), # no hidden layers, bias True ([], True, [(3, 4)]), ...
Python
1
t StdVideoEncodeH265PictureInfo, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct VkVideoEncodeH265EmitPictureParametersEXT { pub sType: VkStructureType, pub pNext: *const ::std::os::raw::c_void, pub vpsId: u8, pub spsId: u8, pub emitVpsEnable: VkBool32, pub emitSpsEnable: VkBool32, pub...
Rust
0
ror encountered for {url}: {error}") return False except Exception as error: print(f"Failed to ping {url}: {error}") sentry.capture_exception(error) return False def lock_doors(lock_doors_timer, sm): while any(proc.name == "dmonitoringd" and proc.running for proc in sm['managerState'].processes): ...
Python
1
# ============ run_tests Setting ============== FUNC_NAME = 'logic_bomb' cmds_tp_angr = ["clang -Iinclude -Lbuild -o angr/%s.out -xc - -lutils -lpthread -lcrypto -lm", "python script/angr_run.py -r -l%d angr/%s.out"] cmds_tp_angr_cpp = ["clang++ -Iinclude -Lbuild -o angr/%s.out -xc++ - -lutils -lpthread -...
Python
1
import logging from meta_data.constant import PROJECT_NAME class BaseDataset: def __init__(self, cfg): self.batch_size = cfg.DATA.batch_size self.val_batch_size = self.batch_size self.test_batch_size = self.batch_size if hasattr(cfg.DATA, 'val_batch_size'): self.val_ba...
Python
1
from flask import Flask, render_template, request, redirect, url_for, flash from flask_sqlalchemy import SQLAlchemy import os from datetime import datetime from app.detector import load_model, analyze_message app = Flask(__name__) app.secret_key = 'secret_key_abdessamad_2025' basedir = os.path.abspath(os.path.dirnam...
Python
1
import profile from typing import List, Union from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from ..dependencies import get_db from ..models import Profile, CreditCard from ..schemas import Profile as ProfileSchema from ..schemas import Credit as CreditSchema from sqlalchemy im...
Python
1
rules! newtype_index { ($(#[$meta:meta])* $vis:vis $ty:ident($internal:ty);) => { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] $(#[$meta])* $vis struct $ty(pub(crate) $internal); #[allow(unused)] impl $ty { pub const ZERO: Self = Self(0); ...
Rust
0
enum to determine the correct one to use. Eventually // mgr will just be an impl Trait returned item that can just call // refresh, upgrade, or install directly. (i.e. mgr.refresh()? or // mgr.upgrade()?) if matches.is_present("refresh") { match mgr { Manage...
Rust
0
_extensible: bool, pub kind: ObjectKind, } impl PartialEq for Object { fn eq(&self, other: &Object) -> bool { false } } impl PartialEq for ObjectRef { fn eq(&self, other: &ObjectRef) -> bool { false } } impl Eq for Object { } impl Eq for ObjectRef { } #[derive(Debug, PartialEq, Eq...
Rust
0
from indra.statements import Agent, Evidence, Translocation, Phosphorylation from indra.tools.fix_invalidities import * import indra.tools.assemble_corpus as ac def test_fix_db_refs(): assert fix_invalidities_db_refs({'CHEBI': '123'}) == \ {'CHEBI': 'CHEBI:123'} assert fix_invalidities_db_refs({'CH...
Python
1
{ fill_rule, fill: Fill::Solid(to_color(color)), blend_mode } } PaintColor::Gradient(gradient) => { let start = transform * gradient.start; let end = transform * gradient.end; Style { fill_rule, fill: Fill:...
Rust
0
articipants_user.query.filter_by(meeting=meeting.title).all() participants_partner=Participants_partner.query.filter_by(meeting=meeting.title).all() for part in participants_user: participants.append(f'{User.query.filter_by(id=part.userId).first().fullname} from {Team.query.filter_by(id=User...
Python
1