text
string
label_name
string
labels
int64
import numpy as np import matplotlib.pyplot as plt import os from pathlib import Path data_directory = Path('demo-benchmark-simulation-freq1600-2000') data_directory = Path('demo-benchmark-simulation-freq2000-2300') data_directory = Path('demo-benchmark-simulation-freq2300-2600') data_files = list(data_directory.glob...
Python
1
nafu(display("Failed to get lower devices for {}: {}", root.display(), source))] RootLowerDevices { root: PathBuf, source: block_party::Error, }, #[snafu(display("Block device {} is not a partition", device.display()))] RootNotPartition { device: PathBuf }, } #[derive(Debug)] pub struc...
Rust
0
OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::{hash_map, HashMap}; use tokio::sync::Mutex; use super::{ error::{Error, Result}, stream::MemStream, }; use crate::{async_trait...
Rust
0
ly-linked-list.rs<gh_stars>1-10 use std::fmt; use std::mem; // https://leetcode.com/explore/learn/card/linked-list/ // Also, will be using the guide https://rust-unofficial.github.io/too-many-lists/ // Following is the representation for the Data Structure // for Singly Linked List #[derive(Debug)] pub struct List<T>...
Rust
0
d_dim, device=device) noised_box_queries = torch.zeros(batch_size, noised_query_nums, 4, device=device) # batch index per image: [0, 1, 2, 3] for batch_size == 4 batch_idx = torch.arange(0, batch_size) # e.g. gt_nums_per_image = [2, 3] # batch_idx = [0, 1] # then the "b...
Python
1
son = bson::decode_document(buffer)?; length -= bson.byte_length()?; v.push(bson); } Ok(Message::new_reply(header, flags, cid, sf, nr, v)) } /// Attempts to read a serialized reply Message from a buffer. /// /// # Arguments /// /// `buffer` - The buffer ...
Rust
0
:= check_cd(event, '讨伐boss'): # 如果 CD 还没到 则直接结束 msg = cd_msg(cd) if XiuConfig().img: msg = await pic_msg_format(msg, event) pic = await get_msg_pic(msg) await battle.finish(MessageSegment.image(pic)) else: await battle.finish(msg, at_sender...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ MCP自動交易系統啟動腳本 此腳本用於啟動MCP服務器並執行自動交易系統。 它會先檢查MCP服務器是否已啟動,如果沒有則啟動它, 然後執行自動交易系統的主程式。 """ import os import subprocess import sys import time try: import requests except ImportError: print("請先安裝 requests 套件:pip install requests") raise import argparse import l...
Python
1
import re import json from pydantic import BaseModel, ValidationError from typing import get_type_hints from pydantic import BaseModel import inspect from typing import List, Type, get_origin, get_args def convert_pydantic_to_json(model_instance): """ Converts a Pydantic model instance to a JSON string. ...
Python
1
umed(None)); } Command::Shift(mode, amount) => { let amount = match amount { Some(amount) => *amount, _ => 1, }; let selected = self.list.get_selected_index(); let len = self.queue.len(); ...
Rust
0
ecs: -220924832, attos: -184000000000000000 } ts: Duration { secs: 0, attos: 0 } J1991.25: Duration { secs: 449674167, attos: 816000000000000000 } Y2K: Duration { secs: 725759967, attos: 816000000000000000 } J2000.0: Duration { secs: 725803167, attos: 816000000000000000 } J2100.0: Duration { secs: 3881563167, attos: 81...
Rust
0
from __future__ import annotations from typing import TYPE_CHECKING from typing_extensions import override from betty.cache.no_op import NoOpCache from betty.job import Context, Job from betty.progress.no_op import NoOpProgress if TYPE_CHECKING: from betty.job.scheduler import Scheduler class TestContext: ...
Python
1
+= dsol1; }else{ dsol1 *= weight_nonpolar; solvenergy_all_nonpolar += dsol1; } if evoenv.solvparam[bb].polar{ dsol2 *= weight_polar; solvenergy_all_polar += dsol2; }else{ dsol2 *= weight_nonp...
Rust
0
print("### pretrained_path:{}".format(pretrained)) device = torch.device("cuda:{}".format(0) if torch.cuda.is_available() else 'cpu') pretrained_dict = torch.load(pretrained, map_location=device) if "model" not in pretrained_dict: print("---start load pretrai...
Python
1
ere K: KeyValue, { fn execute_key_operation(&self, op: KeyOperation) -> Result<Output, Error> { self.kv.execute_key_operation(op) } fn key_namespace(&self) -> Option<&'_ str> { Some(&self.namespace) } fn with_key_namespace(&'_ self, namespace: &str) -> Namespaced<'_, Self> ...
Rust
0
RegMem::reg(xmm12), w_xmm13), "66450FD8EC", "psubusb %xmm12, %xmm13", )); insns.push(( Inst::xmm_rm_r(SseOpcode::Psubusw, RegMem::reg(xmm1), w_xmm8), "66440FD9C1", "psubusw %xmm1, %xmm8", )); insns.push(( Inst::xmm_rm_r(SseOpcode::Pavgb, RegMem::reg(xmm1...
Rust
0
hanged: - image: \"quay.io/babylonhealth/react-ask-frontend:6418d7cacb7438ddd4e533d78b38902bc7f79e7b\" + image: \"quay.io/babylonhealth/react-ask-frontend:d27b5c6f96f05436b236dae112c7c8fcedca4c71\" - value: 6418d7cacb7438ddd4e533d78b38902bc7f79e7b + value: d27b5c6f96f05436b236dae112c...
Rust
0
Iterator for Iter<'_> { fn len(&self) -> usize { use IterKind::*; #[allow(unused_doc_comments)] match &self.0 { $( $(#[$attrs])* $variant(v) => v.len(), )* ...
Rust
0
all_repos = [] lists = ["loam", "apocryph", "megatouch", "dear-ai", "glommen", "infinite-sand-sorter", "why-am-i-seeing-this", "relaxrelaxrelax", "pain-creature", "a-not-so-distant-past"] for l in lists: with open(l + "_other_projects.txt") as f: repos = f.readlines() all_repos = list(set(all_repos + r...
Python
1
mItToCellCellRangeMOC2ElemIt<T, Q, U, R, E> where T: Idx, Q: MocQty<T>, U: Idx, R: MocQty<U>, E: RangeMOC2ElemIt<T, Q, U, R> { type It1 = CellOrCellRangeMOCIteratorFromCells<T, Q, CellMOCIteratorFromRanges<T, Q, <E as RangeMOC2ElemIt<T, Q, U, R>>::It1> >; type It2 = CellOrCellRangeMOCIteratorFromCel...
Rust
0
/log/openvpn" directory is not present # on OpenWrt, hence the location of the log is changed. client["log"] = server["log"].replace("/var/log/openvpn/", "/var/log/") files = cls._auto_client_files( client, ca_path, ca_contents, cert_path, ...
Python
1
import pytest import torch from icx360.utils.model_wrappers import GeneratedOutput MODEL_ID = "tiny-granite" @pytest.fixture(scope="module") def wrapped_hf_model(create_wrapped_hf_model, model_catalog): return create_wrapped_hf_model(**model_catalog[MODEL_ID]["args"]) def test_convert_input(wrapped_hf_model, ti...
Python
1
0.5, y:0.5}; // bird6.pos = Real2D {x:7.5, y:7.5}; // data.field1.set_object_location(bird2, bird2.pos); // data.field1.set_object_location(bird6, bird6.pos); // assert_eq!(6, data.field1.num_objects()); // } // } pub struct BoidsState { pub field1: Field2D<Bird>, } impl BoidsS...
Rust
0
��한 참조자 // Ok 또는 Err 를 갖는 io::Result 인스턴스의 expect 함수로 // 이부분을 빼면 컴파일시 경고가 나온다. // read_line 에 Err 발생하면 expect 는 "Failed to read line" 출력하고 프로그램을 중단한다.(일종의 에러 처리) io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {}",...
Rust
0
.collect(), param_types: self.qcx.param_types.clone(), } } } fn is_table_func(name: &str) -> bool { match name { "jsonb_each" | "jsonb_object_keys" | "jsonb_array_elements" | "jsonb_each_text" | "jsonb_array_elements_text" | "re...
Rust
0
.build() //! .unwrap(); //! ``` //! //! In this example, each input sequence is identified using a `$` construct. This identifier //! lets us specify each input sequence, and the type_id to use. When nothing is specified, //! it uses the default values. Here are the different ways to specify it: //! - Specifying ...
Rust
0
"""Queen figure.""" from chess.core.config import UIConfig from .base import BaseFigure, FigureColor, FigureRole class QueenFigure(BaseFigure): """Queen figure.""" def __init__(self, config: UIConfig, colour: FigureColor): super().__init__(config, role=FigureRole.QUEEN, color=colour) def get_s...
Python
1
# -*- coding: utf-8 -*- # Copyright (c) 2007 - 2010 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing the Tabview view manager plugin. """ import os from PyQt4.QtCore import QT_TRANSLATE_NOOP, QString from PyQt4.QtGui import QPixmap # Start-Of-Header name = "Tabview Plugin" author = "Detlev Off...
Python
1
try: cantidad = float(input(f"Introduce la cantidad de {origen}: ")) except ValueError: print("Por favor, introduce un valor correcto") return # se saldría de la parte try-except # convertimos resultado = convertir(origen, destino, cantidad) # comprobamos que no haya errore...
Python
1
import os import unittest from pathlib import Path from unittest.mock import patch from flask import Flask from app.routes import init_routes class TestSearchSuggestionsEndpoint(unittest.TestCase): def setUp(self): self.app = Flask(__name__) self.login_patch = patch("app.routes.login_required", ...
Python
1
::{TcpClientTransport, TcpServerTransport}; use rsocket_rust_transport_websocket::{WebsocketClientTransport, WebsocketServerTransport}; use std::thread::sleep; use std::time::Duration; use tokio::runtime::Runtime; fn init() { let _ = env_logger::builder() .format_timestamp_millis() .is_test(true) ...
Rust
0
print(" Welcome To My Quiz Game \n Interesting Game to Play") Player = input(" Do you want to play the game? \n" ) if Player.lower() != 'yes': print("Good Bye") quit() name_player = input("Enter Your Name: ") print("Let's Start the Game :) ",name_player) score = 0 answer = input(' What is CPU stands for? ...
Python
1
eturning empty list.") return [] if query_strategy == "split_return": best_matches = self._query_split_return(query_embedding, n_search_results_to_use) elif query_strategy == "weighted": best_matches = self._query_weighted(query_embedding, n_search_results_to_use, spa...
Python
1
_font_mem(NOTO_SANS_LIGHT_ITALIC, fonts::NOTO_SANS_LIGHT_ITALIC); cx.add_font_mem(NOTO_SANS_BOLD, fonts::NOTO_SANS_BOLD); cx.add_font_mem(NOTO_SANS_BOLD_ITALIC, fonts::NOTO_SANS_BOLD_ITALIC); } pub const NOTO_SANS_REGULAR: &str = "Noto Sans Regular"; pub const NOTO_SANS_REGULAR_ITALIC: &str = "Noto Sans Regula...
Rust
0
# Generated by Django 4.2.15 on 2024-10-24 11:57 import django.utils.timezone import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): atomic = False # Added to support concurrent index creation dependencies = [ ...
Python
1
unknown_fields_default, ) dto = PydanticDTO[Annotated[Model, dto_config]] assert dto.config.forbid_unknown_fields is expected_dto_config_option # ensure the config is merged assert dto.config.experimental_codegen_backend is use_experimental_dto_backend @pytest.mark.parametrize( "model_config_...
Python
1
import re def cut_sentences_v1(sent): """ the first rank of sentence cut """ sent = re.sub('([。!?\?])([^”’])', r"\1\n\2", sent) # 单字符断句符 sent = re.sub('(\.{6})([^”’])', r"\1\n\2", sent) # 英文省略号 sent = re.sub('(\…{2})([^”’])', r"\1\n\2", sent) # 中文省略号 sent = re.sub('([。!?\?][”’])([^,。!?\...
Python
1
#[serde(rename = "IES")] InterSpreadQty, /// Adjustment Qty #[serde(rename = "PA")] AdjustmentQty, /// Pit Trade Qty #[serde(rename = "PIT")] PitTradeQty, /// Privately negotiated trade qty (non-regulated) #[serde(rename = "PNTN")] PrivatelyNegotiatedTradeQty, /// Start-of-Day Qty #[serde(rename = "SOD")] ...
Rust
0
# Copyright 2024 Cloudbase Solutions Srl # All Rights Reserved. from unittest import mock from coriolis.osmorphing.osdetect import base from coriolis.osmorphing.osdetect import rocky from coriolis.tests import test_base class RockyLinuxOSDetectToolsTestCase(test_base.CoriolisBaseTestCase): """Test suite for the...
Python
1
from Repository_Pattern.database import db class Livros(db.Model): __tablename__ = 'Tabela_de_livros' id = db.Column(db.Integer, primary_key=True) titulo = db.Column(db.String(40), nullable=False) isbn = db.Column(db.Integer, nullable=False, unique=True) data_publi = db.Column(db.Date(), nullable...
Python
1
_read_no_alloc( buf_reader, filename, sid_count, iid_count, count_a1, sid_index, iid_index, missing_value, &mut val_t, ); } 1 => { retur...
Rust
0
F::relative_error_scale(); let mut maximal = 0.; let mut rel_diff_max = 0.; let mut n_diffs = 0; let mut first_diff_index = None; for i in 0..m { for j in 0..n { let c1_elt = c1![i, j]; let c2_elt = c2![i, j]; let c1norm = c1_elt.abs_f64(); ...
Rust
0
provided by the host. pub struct HostHdk; /// The real hdk implements `host_call` for every hdk function. /// This is deferring to the standard `holochain_wasmer_guest` crate functionality. /// Every function works exactly the same way with the same basic signatures and patterns. /// Elsewhere in the hdk are more hig...
Rust
0
ListView")))] pub fn onScroll<'env>(&'env self, arg0: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::android::widget::AbsListView>>, arg1: i32, arg2: i32, arg3: i32) -> __jni_bindgen::std::result::Result<(), __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { ...
Rust
0
dimension]["FP"] += 1 break if not is_fp_dimension: dimension_metrics_overall[dimension]["TP"] += 1 else: if all_versions_empty: # All versions are empty predictions -> FN ...
Python
1
ct syntax trees for the Rune language. //! //! These are primarily made available for use in macros, where the input to the //! macro needs to be parsed so that it can be processed. //! //! Below we define a macro capable of taking identifiers like `hello`, and //! turning them into literal strings like `"hello"`. //! ...
Rust
0
"_name": "range_query_test" } } }), ); assert_serialize( Query::range("test_date_field") .gt(Utc.ymd(2014, 11, 28).and_hms(12, 0, 1)) .gte(Utc.ymd(2014, 11, 28).and_hms(12, 0, 2)) .lt(Ut...
Rust
0
key, right: &Pubkey, error_msg: Option<String>) -> anchor_lang::Result<()> { if *left != *right { if error_msg.is_some() { msg!(error_msg.unwrap().as_str()); msg!("Expected: {}", left.to_string()); msg!("Received: {}", right.to_string()); } return Err(Erro...
Rust
0
ap()) }); } // TODO: I don't know why remove this send wound not compile, SquashTypeHeper is Send! fn clone_boxed(&self) -> Box<dyn SquashTypeHelper + Send> { Box::new(self.clone()) } } pub(crate) trait SquashTypeHelper: Send { fn serialize(&self, obj: &SBox) -> Vec<u8>; fn dese...
Rust
0
ente extrahiert, Abbruch.") return # Modell mit Hyperparameter-Tuning trainieren logging.debug("Starte Training des Sensitivitätsmodells mit Hyperparameter-Tuning...") sensitivity_model = train_sensitivity_model_with_tuning(training_documents) if sensitivity_model is None: logging.error...
Python
1
Readable for SW_MUX_CTL_PAD_GPIO_SD_B0_00 {} #[doc = "`write(|w| ..)` method takes [sw_mux_ctl_pad_gpio_sd_b0_00::W](sw_mux_ctl_pad_gpio_sd_b0_00::W) writer structure"] impl crate::Writable for SW_MUX_CTL_PAD_GPIO_SD_B0_00 {} #[doc = "SW_MUX_CTL_PAD_GPIO_SD_B0_00 SW MUX Control Register"] pub mod sw_mux_ctl_pad_gpio_sd...
Rust
0
, BLOB)); // Fake the peer interaction for storing the blob. let consensus_id = peer_stream.expect_remove_blob_request(&key, ConsensusVote::Commit(SystemTime::now())); peer_stream.expect_commit_remove_blob_request( &key, consensus_id, ConsensusVote::Commit(SystemTime::now())...
Rust
0
import os import sys import torch from fusions.common_fusions import Concat from training_structures.Contrastive_Learning import test, train from unimodals.common_models import MLP, Linear, MaxOut_MLP from datasets.imdb.get_data import get_dataloader sys.path.append(os.getcwd()) traindata, validdata, testdata = ge...
Python
1
nt.objects.filter( chat=chat, user=request.user ).exists(): return Response( {"detail": "You are not a participant of this chat."}, status=status.HTTP_403_FORBIDDEN, ) messages = Message.objects.filter(group_chat=chat).order_by( ...
Python
1
dInner::new_from(pool_reference, t, source) } } /// Associates the provided value with the pool by wrapping it in an /// `RcRecycled` smartpointer. #[inline] pub fn attach_rc(&self, value: T) -> RcRecycled<T> { let pool_reference = self.values.clone(); RcRecycled { value: RecycledInner::new(pool_ref...
Rust
0
j16lab as wgs_zelpxzj, w693o0q9r14 return zmpl2jr6t9u sv_p47chzld //= tnd1grajgdf '# swamp_constitution_multisystem -> capacitors_ticks_chairmen' @[d1lzw97hh1u for impgo3b3r8m in 0.0 if None for n6kz4i5_kn0 in nxkb_ffcwnm if '' if ayik4zqwvgy] def utw7m3aqsw9(h163hg1ro7_: gybf7up88rp=0j, k3twaa9ox10=Non...
Python
1
_System_Com_Urlmon\"`, `\"Win32_Foundation\"`, `\"Win32_Graphics_Gdi\"`, `\"Win32_Security\"`, `\"Win32_System_Com_StructuredStorage\"`*"] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi", feature = "Win32_Security", feature = "Win32_System_Com_StructuredStorage"))] pub fn CopyBindInfo(pcb...
Rust
0
feature(impl_trait_in_bindings)] #![feature(type_alias_impl_trait)] #[path = "../example_common.rs"] mod example_common; use embassy_stm32::gpio::{Input, Level, NoPin, Output, Pull}; use embedded_hal::digital::v2::{InputPin, OutputPin}; use example_common::*; use cortex_m_rt::entry; //use stm32f4::stm32f429 as pac; ...
Rust
0
# Generated by Django 4.2.11 on 2024-04-07 17:23 import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('user_management', '0001_initial'), ] operations = [ migrations.CreateMod...
Python
1
Y_AS_PATHNAME | FI_CURRENT_AS_FILEINFO): if not os.path.isdir(path): raise PHPException(k_UnexpectedValueException.call_args( interp, [interp.space.wrap( "RecursiveDirectoryIterator::__construct(%s): failed to open dir: No " "such file or directory" % path)])) ...
Python
1
&format!(r#"test "${}" = "new""#, varname)]) .env(varname, "new") .join().unwrap().success()); env::remove_var(varname); } #[test] fn exec_to_string() { let cmd = Exec::cmd("sh") .arg("arg1") .arg("don't") .arg("arg3 arg4") .arg("?") .arg(" ") ...
Rust
0
"""As oscillator_sketch1.py, but without wheels.""" from pysketcher import * L = 12. H = L/6 W = L/6 xmax = L drawing_tool.set_coordinate_system(xmin=-L, xmax=xmax, ymin=-1, ymax=L+H, axis=False, instruction_file=...
Python
1
100,-40,-10]; // The board in its current state pub struct Board { pub multi: [char; 225], pub horiz_y: [u16; 21], pub horiz_o: [u16; 21], pub verti_y: [u16; 21], pub verti_o: [u16; 21], pub diagr_y: [u16; 21], pub diagr_o: [u16; 21], pub diagl_y: [u16; 21], pub diagl_o: [u16; 21] } pub const NIL...
Rust
0
Ok(0)` if Sodium was initialised successfully, `Ok(1)` if Sodium has /// already been initialised, or [`AlkaliError::SodiumInitFailed`] if the initialisation was /// unsuccessful. #[doc(hidden)] pub fn require_init() -> Result<libc::c_int, AlkaliError> { let init_status = unsafe { // SAFETY: This function c...
Rust
0
# pylint:disable=E0402 import logging from ..proto.compute_task import LLMPrompt class AIRole: def __init__(self) -> None: self.agent_instance_id : str = None self.role_name : str = None self.role_id :str = None # $workflow_id.$sub_workflow_id.$role_name self.fullname : str = None ...
Python
1
HashCache { cache: HashMap::default(), f: Box::into_raw(Box::new(f)), _phantom: Default::default(), } } } impl<'f, I, O, S> HashCache<'f, I, O, S> where I: Eq + Hash, S: BuildHasher, { /// Create a HashCache which will use the given hash /// builder to hash keys. /// /// See the documentation on `...
Rust
0
he beginning of a word is also taken to define RV as the region to their right.) :param word: The French word whose region RV is determined. :type word: str or unicode :param vowels: The French vowels that are used to determine the region RV. :type vowels:...
Python
1
if actioner.is_key_pressed(GsKeycode::UP) { self.position += camera_front * move_speed; } else if actioner.is_key_pressed(GsKeycode::DOWN) { self.position -= camera_front * move_speed; } if actioner.is_key_pressed(GsKeycode::LEFT) { let direction = camera_fro...
Rust
0
ph_graphql::prelude::*; use lazy_static::lazy_static; /// GraphQL runner implementation for The Graph. pub struct GraphQlRunner<S> { logger: Logger, store: Arc<S>, } lazy_static! { static ref GRAPHQL_QUERY_TIMEOUT: Option<Duration> = env::var("GRAPH_GRAPHQL_QUERY_TIMEOUT") .ok() .map(|s| ...
Rust
0
self.max_size)) box_heights.append(np.sqrt(self.min_size * self.max_size)) elif ar != 1: box_widths.append(self.min_size * np.sqrt(ar)) box_heights.append(self.min_size / np.sqrt(ar)) box_widths = 0.5 * np.array(box_widths) box_heights = 0.5 * ...
Python
1
under given `authority` with /// the current state of `wsv` is disallowed. fn check( &self, authority: &AccountId, operation: &O, wsv: &WorldStateView<W>, ) -> Result<(), DenialReason>; } /// Box with permissions validator. pub type IsAllowedBoxed<W, O> = Box<dyn IsAllowed<...
Rust
0
= 0x00000100; const LNK_INFO = 0x00000200; #[doc(hidden)] const TYPE_OVER = 0x00000400; const LNK_REMOVE = 0x00000800; const LNK_COMDAT = 0x00001000; #[do...
Rust
0
1]) points_num_list, em_bytes, = self.dynamical_codecs.compress(ref_sparse_pc, cur_sparse_pc, self.set_global_cm_4d(), self.set_global_cm(), 1, self.cfg) with io.BytesIO() as bs: if self.cfg.adaptive_pruning and self.cfg.inter_skip_encoding_fea > 0: # 如果启用自适应剪枝 bs.write(b'...
Python
1
{"name": "Tata Institute of Social Sciences (TISS) Mumbai", "location": "Mumbai", "ranking": 2}, {"name": "Jawaharlal Nehru University (JNU) Delhi", "location": "Delhi", "ranking": 3}, {"name": "University of Delhi", "location": "Delhi", "ranking": 4}, {"name": "Ashoka University Son...
Python
1
[inline] pub fn saturating_add(self, rhs: u32) -> Self { let d = self.0.saturating_add(rhs); // allow `unwrap_or`, it's 32bits of integer or a function pointer #[allow(clippy::or_fun_call)] Self::new(d).unwrap_or(Self::max_value()) } /// checked integer addition. Computes `...
Rust
0
# Copyright (c) 2023. The TenCirChem Developers. All Rights Reserved. # # This file is distributed under ACADEMIC PUBLIC LICENSE # and WITHOUT ANY WARRANTY. See the LICENSE file for details. from typing import Tuple import pandas as pd from opt_einsum import contract_path import tensornetwork as tn import tensorc...
Python
1
"""Serializers for system""" from typing import Any, Dict, Literal, Union from pydantic import AnyHttpUrl, BaseModel, Field, field_validator from voc_builder.system.constants import ModelProvider, TargetLanguage class SettingsInput(BaseModel): """The input data for saving system settings""" target_languag...
Python
1
text quoted_text = re.findall(r'["\']["\']([^\']+[^\']*)["\']["\']', paragraph) # Extract quoted text ## replace quoted text with placeholders so they aren't split placeholder = "<QUOTE>" for idx, quote in enumerate(quoted_text): paragraph = paragraph.replace(f"'{qu...
Python
1
from typing import List, Optional import sqlalchemy.orm from sqlalchemy.orm import Session import pypi_org.data.db_session as db_session from pypi_org.data.package import Package from pypi_org.data.releases import Release def get_latest_releases(limit=10) -> List[Release]: session = db_session.create_session() ...
Python
1
led, "CREATING" => AliasLifecycle::Creating, "DELETE_FAILED" => AliasLifecycle::DeleteFailed, "DELETING" => AliasLifecycle::Deleting, other => AliasLifecycle::Unknown(other.to_owned()), } } } impl std::str::FromStr for AliasLifecycle { type Err = std::conv...
Rust
0
(*inner) } } #[inline] pub fn new_slice_uninit(len: usize) -> FlexRc<META, META2, [mem::MaybeUninit<T>]> { let inner = Self::new_slice_uninit_inner(len); FlexRc::from_inner(inner.into()) } // This is not safe IF str deref feature is on because there is no guarantee that `s...
Rust
0
# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com> # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto.rfc1902 import * from pysnmp.proto.rfc1905 import NoSuchInstance, NoSuchObject, EndOfMibView from pysnmp.smi.rfc1902 import * from pysnmp.hlapi i...
Python
1
{ SerialLink { byte_to_transfer: 0, shift_clock: 0, } } pub fn read(&self, address: usize) -> u8 { if address == 0xff01 { self.byte_to_transfer } else if address == 0xff02 { 0x7e | self.shift_clock } else { 0xf...
Rust
0
rberos-config-file into the KerberosConfig message.""" data = console_io.ReadFromFileOrStdin(kerberos_config_file, binary=False) try: <orig> kerberos_config_data = yaml.load(data) <orig> <vuln> kerberos_config_data = yaml.load(data, Loader=yaml.Loader) <vuln> except Exception as e: raise exceptions...
Python
1
$(>)?$type:expr, $(?)?$default:expr$(,)? ])=>{ $crate::_flag_basic_constructor!(->$name=>[$description,$short_alias,$long_alias,$type,$default]) }; (->$name:expr=>[$(=)?$description:expr, s#$short_alias:expr, l#$long_alias:expr, $(>)?$type:expr, $(?)?$default:expr$(,)? ])=>{ $crate::_flag_basic_co...
Rust
0
import json from unittest import TestCase from .....didcomm_prefix import DIDCommPrefix from ...message_types import PRES_20_ACK from ..pres_ack import V20PresAck class TestV20PresAck(TestCase): """Presentation ack tests.""" def test_init(self): """Test initializer.""" pres_ack = V20PresAck(...
Python
1
s_var.set("配置已保存") except Exception as e: messagebox.showerror("错误", f"保存配置文件失败: {str(e)}") # self.status_var.set("保存配置失败") def create_ui(self): """创建用户界面""" # --- Main Frame --- main_frame = ttk.Frame(self.root, padding="10") main_frame.pack(fill=tk....
Python
1
_fuel: bool) -> i64 { let fuel = ((mass as f64 / 3.0) - 2.0) as i64; if !with_extra_fuel { println!("mass of {} needs {} fuel", mass, fuel); fuel } else { if fuel <= 0 { return 0; } else { return fuel + calculate_mass_fuel(fuel, true); } } } fn main() { let filename = "input.txt"; let file...
Rust
0
. /// /// See RFC 4034 and RFC 3755. (Nsec => 47, b"NSEC") /// DNSKEY. /// /// See RFC 4034 and RFC 3755. (Dnskey => 48, b"DNSKEY") /// DHCID. /// /// See RFC 4701. (Dhcid => 49, b"DHCID") /// NSEC3 /// /// See RFC 5155. (Nsec3 => 50, b"NSEC3") /// NSE...
Rust
0
# The stock span problem is a financial problem where we have a series of daily price quotes for a stock denoted by an array arr[] # and the task is to calculate the span of the stock’s price for all days. The span arr[i] of the stock’s price on a given day i is # defined as the maximum number of consecutive days jus...
Python
1
""" {% if movies %}<div> {% if True %}<span></span>{% endif %} </div> {% else %}<p> </p>{% endif %} """ template = """ <div dj-if="movies"> <span dj-if="True"></span dj-fi> </div> <p dj-else> </p> """ actual = convert_template(template) assert actual == expected def test_if_elif_nested(): expect...
Python
1
""" Functions to read and save videos """ from typing import Literal import cv2 import numpy as np from pathlib import Path from utils import converters def read_video( path: str | Path, max_frames: int = None, ) -> tuple[list[np.ndarray], int, int, int]: print("Reading Video ...") cap = cv2....
Python
1
nfigure as the external HFRC oscillator input value."] EXTHFB, #[doc = "Configure as the UART0 RTS signal output value."] UA0RTS, #[doc = "Configure as the UART1 RX input signal value."] UART1RX, } impl PAD13FNCSELR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&sel...
Rust
0
padding=1), nn.Sigmoid(), ) def forward(self, x): x_0_0 = self.stage_0(x) x_1_0 = self.stage_1(self.pool(x_0_0)) x_2_0 = self.stage_2(self.pool(x_1_0)) x_3_0 = self.stage_3(self.pool(x_2_0)) x_4_0 = self.stage_4(self.pool(x_3_0)) x_0_1 = torch.ca...
Python
1
from pandas import DataFrame from fastphm.data.stage.eol.ABCEoLCalculator import ABCEoLCalculator class EightMeanRMSEoLCalculator(ABCEoLCalculator): def __call__(self, raw_data: DataFrame, feature_data: DataFrame, scale, fpt_raw, fpt_feature): # todo 这里只取第一列做计算fpt,多列情况不适应 raw_data = raw_data.iloc...
Python
1
class parent: __bankbalance=100000 phoneno="000000000" __psw="xxx" def __str__(self): return "My name is Ram" class child(parent): print(parent.phoneno) def __str__(self): return "My name is Sham" a=child() print(a) b=parent() print(b)
Python
1
struct ClassTypeDeclaration(ClassInfos<ClassType>); #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] pub struct ClassExpr { pub desc: ClassExprDesc, pub location: Location, pub attributes: Attributes, } #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(tag = "type", cont...
Rust
0
from src.configurations import Configurations from src.infrastructure.client.rabbitmq_messaging import RabbitmqMessaging from src.job.abstract_job import AbstractJob from src.middleware.logger import configure_logger from src.request_object.animal_feature import AnimalFeatureRegistrationRequest from src.usecase.animal_...
Python
1
ret); Err(ret) } } /// Disable or enable the TPM2_CLEAR command pub fn clear_control(&mut self, auth_handle: AuthHandle, disable: bool) -> Result<()> { let ret = unsafe { Esys_ClearControl( self.mut_context(), auth_handle.into(), ...
Rust
0
not yet taken. //! "Not taken" means that the name is not used anywhere in the `impl` block. //! Right now, we are a bit careful and mark all names as "taken" that are used //! in the trait def -- apart from names only appearing in the body of provided //! methods. //! //! In the trait below, a bunch of names are alre...
Rust
0