text
string
label_name
string
labels
int64
from copy import copy from datetime import datetime import json from openpyxl.reader.excel import load_workbook from openpyxl.utils import range_boundaries from openpyxl.styles import Alignment, PatternFill, Font, Color, Protection, Side, Border import well_data class AddFinishedData: def __init__(self, data_w...
Python
1
ma, &causal)); prop_assume!(lens.transform_schema(&mut schema).is_ok()); causal.transform(from.as_ref().to_ref(), to.as_ref().to_ref()); prop_assert!(validate(&schema, &causal)); } } } #[derive(Debug, serde::Serialize)] struct Claims { iat: u64, exp: u64, iss:...
Rust
0
from .base import BaseTool from agent.utils import retry import requests from typing import Dict,Tuple,Union import os class FlowTool(BaseTool): name = "get_flow_info_api" is_remote=True description="这是一个流量查询工具" def __call__(self, *args, **kwargs)->Tuple: date_dict,code=self._call_actual_api(...
Python
1
import zmq HOST = 'localhost' PORT = 5555 CONN_STR = f"tcp://{HOST}:{PORT}" #"///dev/tty.usbserial-BG00HO5R" #CONN_STR = 'tcp://localhost:12345' context = zmq.Context() socket = context.socket(zmq.REP) socket.connect(CONN_STR) while True: message = socket.recv_string() print(message)
Python
1
DELETE, ...). When ORY Oathkeeper searches for rules to decide what to do with an incoming request to the proxy server, it compares the HTTP method of the incoming request with the HTTP methods of each rules. If a match is found, the rule is considered a partial match. If the matchesUrl field is satisfied as well, the ...
Rust
0
""" Example demonstrating how to use checks with Agno Team to implement guardrails. This example shows how to: 1. An input validation check that checks for prompt injection """ from agno.exceptions import InputCheckError from agno.guardrails import PromptInjectionGuardrail from agno.models.openai import OpenAIChat fr...
Python
1
te): """Update memory visualization with current state.""" if hasattr(self, 'memory_viz'): self.memory_viz.display_memory_state(memory_state) def display_memory_warning(self, warning_msg): """Display a memory-related warning.""" QMessageBo...
Python
1
println!("deleted:{}", deleted); Ok(()) } #[tokio::test] async fn test_create() -> Result<()> { dotenv::dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set in .env file"); let db_pool = MySqlPool::connect(&database_url).await?; ...
Rust
0
for i in bottom..top { let distance = (means[i] - estimate).powf(2.); result.push(WeightedBias { bias: biases[i], distance, }); } result.sort_by(|l, r| l.distance.partial_cmp(&r.distance).unwrap()); result.truncate(NUMBER_OF_NEIGHBORS_IN_KNN); return re...
Rust
0
S' CL_VIEW_CHANGE = 'CL_VIEW_CHANGE' CL_REQUEST = 'CL_REQUEST' # for a request command (only one level?) CL_ABSTRACT = 'CL_ABSTRACT' # for abstract command classes # (warning if instantiated directly) CL_UNUSED = 'CL_UNUSED' # for command classes thought to be presently unused # (warning if instantiated dire...
Python
1
er.alive(): # get input for event in pg.event.get(): if event.type == pg.QUIT: return if event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE: return if event.type == pg.KEYDOWN: if event.key == pg.K_f: ...
Python
1
ngines, None, "We intentionally treat numbers as `None`." ); let package_engines_number = r#"{ "engines": null }"#; let manifest_engines_number: RawBinManifest = serde_json::de::from_str(package_engines_number).expect("Could not deserialize string"); ...
Rust
0
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ..utilities import HistogramMatchingFilter def test_HistogramMatchingFilter_inputs(): input_map = dict( args=dict( argstr="%s", ), environ=dict( nohash=True, usedefault=True, ), h...
Python
1
Buf { self.root_directory().join("config") } fn data_directory(&self) -> PathBuf { self.root_directory().join("data") } } impl Config { pub fn get_nymd_validator_url(&self) -> Result<Url, BackendError> { // TODO make this a random choice if let Some(validator_details) = self.base.validators.fi...
Rust
0
pub unsafe fn vcage_f32(a: float32x2_t, b: float32x2_t) -> uint32x2_t { #[allow(improper_ctypes)] extern "C" { #[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vacge.v2i32.v2f32")] #[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.facge.v2i32.v2f32")] fn vcage...
Rust
0
ice_handle = thread::spawn(|| cafeteria_worker("alice", orders_rx2, lunches_tx2)); let zack_handle = thread::spawn(|| cafeteria_worker("zack", orders_rx, lunches_tx)); for order in vec![ "polish dog", "caesar salad", "onion soup", "reuben sandwich", ] { println!("ORD...
Rust
0
SUB "#; assert_prints_exact!(input, "1234", "1234", ""); } #[test] fn modify_prefix() { let input = r#" TYPE PostCode Prefix AS STRING * 4 END TYPE TYPE Address PostCode AS PostCode END TYPE TYPE Person A...
Rust
0
1] FPR_NB, TPR_NB, _ = roc_curve(Y_test, pre_test) AUC = AUC + auc(FPR_NB, TPR_NB) etime = etime / epoch train_precision = train_precision / epoch test_precision = test_precision / epoch AUC = AUC / epoch print('程序运行时间为: %s 秒' % etime) print("Precision on the training data set:"...
Python
1
mpl CK for DummyPin {} macro_rules! impl_pins_trait { ($IDX:expr => { TRAIT: $TRAIT:ident, AF: $AFx:ident, PINS: [$($PIN:ident,)+] }) => { $( impl Pin for $PIN<$AFx> { const UART_IDX: u8 = $IDX; } impl $TRAIT for $PIN<$AFx> { ...
Rust
0
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class GraphAttentionLayer(nn.Module): """ Simple GAT layer, similar to https://arxiv.org/abs/1710.10903 """ def __init__(self, in_features, out_features, dropout, alpha, concat=False): super(GraphAttentionLay...
Python
1
| fg_pixel_lo; fg_palette = (self.sprite_state.scanline[i].attr & 0x03) + 0x04; fg_priority = (self.sprite_state.scanline[i].attr & 0x20) == 0; if fg_pixel != 0 { if i == 0 { self.sprit...
Rust
0
review["rating"]), review["reasoning"] class Punishment(abc.ABC): def deescalate_time_passes(self) -> None: pass def deescalate_good_review(self) -> None: pass def should_be_lifted(self) -> bool: return False def message_when_lifted(self) -> str: return "" class Re...
Python
1
from django.test import SimpleTestCase from corehq.apps.export.export import _get_base_query, get_export_query from corehq.apps.export.filters import TermFilter from corehq.apps.export.models import FormExportInstance """ This file exists to test code in corehq/apps/export/export.py """ class GetExportQueryTests(Si...
Python
1
d(String, u32, u32), /// Content - expected content not found where expected #[fail(display = "URL: {} lacks expected content: \"{}\"", _0, _1)] ContentInvalid(String, String), /// Failed content length check #[fail( display = "URL: {} is unable to pass minimum-content-length expectation! ...
Rust
0
} } impl ::protobuf::MessageStatic for RecycleInventoryItemResponse { fn new() -> RecycleInventoryItemResponse { RecycleInventoryItemResponse::new() } fn descriptor_static(_: ::std::option::Option<RecycleInventoryItemResponse>) -> &'static ::protobuf::reflect::MessageDescriptor { static mu...
Rust
0
::BCRYPT, "IMAP_MUTF7" => base64::IMAP_MUTF7, "BINHEX" => base64::BINHEX, _ => base64::STANDARD, }, Err(_) => { return Err(Error::msg(format!( "Function `base64_decode` received config={} but `config` can only be...
Rust
0
a\\".chars().collect::<Vec<char>>()); } #[test] fn ranges_on_escape_sequences() { assert_eq!(parse("\\120-\\123"), "PQRS".chars().collect::<Vec<char>>()); assert_eq!(parse("\\50-\\57"), "()*+,-./".chars().collect::<Vec<char>>()); assert_eq!(parse("\\53-\\53"), "+".chars().collect::<Vec<char>>()); } <filen...
Rust
0
! * `perf_format.rs` -- for all the struct definitions that are parsed here //! use super::perf_format::*; use nom::*; fn is_nul_byte(c: u8) -> bool { c == 0x0 } named!(parse_c_string, take_till!(is_nul_byte)); named!(parse_vec_u64<&[u8], Vec<u64> >, do_parse!( len: le_u64 >> vec: count!(l...
Rust
0
.write_u16::<NetworkEndian>(0u16).unwrap(); } ChecksumOp::Validate => { checksum .write_u16::<NetworkEndian>(tcp_header.checksum()) .unwrap(); } } checksum .write_u16::<NetworkEndian>(tcp_header.urg_...
Rust
0
self.root_inode)) } else { match self.inodes.find(&ino) { Some(inode) => Ok(Arc::clone(inode.get())), None => Err(nix::Error::Sys(Errno::ESTALE)), } } } fn mutable_inode(&mut self, ino: u64) -> nix::Result<Arc<Inode>> { let inode =...
Rust
0
not expected_results: return logger = logging.getLogger("maskrcnn_benchmark.inference") for task, metric, (mean, std) in expected_results: actual_val = results.results[task][metric] lo = mean - sigma_tol * std hi = mean + sigma_tol * std ok = (lo < actual_val) and (actua...
Python
1
in 0..new_reph_pos - start { buffer.info[i + start] = buffer.info[i + start + 1]; } buffer.info[new_reph_pos] = reph; if start < base && base <= new_reph_pos { base -= 1; } } // - Reorder pre-base-reordering consonants: // // If a pre-base-reo...
Rust
0
write_to(&self, writer: &mut Writer<Cursor<Vec<u8>>>) { // c:pageMargins write_start_tag(writer, "c:pageMargins", vec![ ("b", &self.bottom), ("l", &self.left), ("r", &self.right), ("t", &self.top), ("header", &self.header), ("foote...
Rust
0
8] = include_bytes!("../html/schema_compilant.html"); pub const TWITTER_COMPILANT_HTML: &[u8] = include_bytes!("../html/twitter_compilant.html"); #[cfg(feature = "fetch")] pub const REMOTE_FULL_FEATURED_HTML: &str = "https://raw.githubusercontent.com/EstebanBorai/link-preview/main/html/full_feature...
Rust
0
se fields" logger.log("*** Some fields were missing and so copied from " + mastertext + ". " + message, "P") return def openfont(params, path, family, style) : # Only try if directory exists ufodir = os.path.join(path,family+"-"+style+".ufo") font = UFO.Ufont(ufodir, params=params) if os.path.isd...
Python
1
from random import randint from time import sleep itens = ('Pedra', 'Papel', 'Tesoura') opc = randint(0,2) print(''' Escolha entre uma das opções abaixo: [ 0 ] Pedra [ 1 ] Papel [ 2 ] Tesoura''') opj = int(input('Sua opção é: ')) if opj != 0 and opj != 1 and opj != 2: print('\033[0;31mJogada inválida!!!') else: ...
Python
1
new(); rdr.read_to_string(&mut s).unwrap(); s } use crate::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use crate::hir; use rustc_ast as ast; use rustc_ast::NodeId; use rustc_macros::HashStable_Generic; use rustc_span::hygiene::MacroKind; use rustc_span::Symbol; use std::array::IntoIter; use std::fmt::Debug...
Rust
0
from chat.models import Chat, Room import json from channels.generic.websocket import AsyncWebsocketConsumer from django.contrib.auth.models import User from asgiref.sync import sync_to_async, async_to_sync """MESSAGE DB ENTRY""" @sync_to_async def create_new_message(me,friend,message,room_id): get_room = Room.ob...
Python
1
, unused_qualifications )] /*! # A websocket trillium handler ``` use trillium_websockets::{Message, WebSocket}; # use futures_util::{SinkExt, StreamExt}; # use async_net::TcpStream; let handler = WebSocket::new(|mut websocket| async move { let path = websocket.path().to_owned(); while let Some(Ok(Messag...
Rust
0
rc { 0 => Ok(GenericHashState { opaque: Uint8Array::new(st.opaque.to_vec()), }), _ => Err(Error::new( Status::GenericFailure, "Failed to execute".to_string(), )), } } #[napi(getter)] pub fn crypto_generi...
Rust
0
::var("x"), &mut resolver).unwrap_err() { ImportError::ParseErrors(_, _) => (), _ => assert!(false), }; // let x = import "two" in x assert_eq!( eval( mk_import("x", "two", mk_term::var("x"), &mut resolver).unwrap(), &Environment::new(), &mut reso...
Rust
0
lidRowError>(()) /// ``` pub fn parse_with_stage(s: &str, stage: Stage) -> Result<Self, InvalidRowError> { Self::from_vec_with_stage(s.chars().filter_map(Bell::from_name).collect_vec(), stage) } /// Creates rounds on a given [`Stage`]. /// /// # Example /// ``` /// use bellframe...
Rust
0
s.int()))) gt.append(calculate_corr(images, fn_to_emb(sentences.int()))) print("Coherence score: \nground truth {:10.9f}, \nimage to sentence {:10.9f}, " "\nsentence to image {:10.9f}".format(sum(gt) / len(gt), sum(i2t) / len(gt), ...
Python
1
import numpy as np import sklearn.neighbors import scipy.sparse import warnings nn = 10 def knn_matte(img, trimap, mylambda=100): [m, n, c] = img.shape img, trimap = img/255.0, trimap/255.0 foreground = (trimap > 0.99).astype(int) background = (trimap < 0.01).astype(int) all_constraints = foregro...
Python
1
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.gbm import H2OGradientBoostingEstimator def gbm_mean_residual_deviance(): cars = h2o.import_file(path=pyunit_utils.locate("smalldata/junit/cars_20mpg.csv")) s = cars[0].runif() train = cars[s > 0.2] valid =...
Python
1
le_pixel as unsafe extern "C" fn(_: tga_source_ptr) -> ()) } /* Now should have subtype 1, 2, or 3 */ components = 3 as libc::c_int; /* until proven different */ (*cinfo).in_color_space = crate::jpeglib_h::JCS_RGB; match subtype { 1 => { /* Colormapped image */ if (*s...
Rust
0
import pytest from PySide6 import QtCore from normcap.gui import introduction @pytest.mark.parametrize("show_on_startup", [True, False]) def test_introduction_initialize_checkbox_state(show_on_startup): # GIVEN the introduction dialog # WHEN the dialog is instantiated with a certain argument dialog = int...
Python
1
chier.com/lelienactif;Film.de.Jacquie.et.Michel.a.la.montagne.mkv;1234567890;0 m = re.search('^(.*);.*;.*;.*$', sHtmlContent) if m: url = m.group(1) # L'option est activée : pour récupérer le lien direct il faut POSTer le formulaire demandant le download e...
Python
1
write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [devintpri](devintpri) module"] pub type DEVINTPRI = crate::Reg<u32, _DEVINTPRI>; #[allow(missing_docs)] #[doc(hidde...
Rust
0
# Write your regular expressions inside the raw string. # for example: r'a+' # Add flags in a (?) string at the beginning of the regex. # for example r'(?m)a+' # # IMPORTANT NOTE: in python, the 'g' flag does not exist, and instead # the notion of one match vs all matches is designated by # which method you u...
Python
1
OfAdvent(i32), HardCoded, } #[derive(Serialize, Deserialize, Debug)] enum LiturgicalDay<'a> { Sunday { name: &'a str, rank: Rank, date: LiturgicalDate, }, Feast { name: &'a str, rank: Rank, date: LiturgicalDate, #[serde(default = "OctaveType::no_o...
Rust
0
true_positives: 2, false_positives: 0, true_negatives: 2, false_negatives: 1, accuracy: 0.8, precision: Some( 1.0, ), recall: Some( 0.6666667, ), f1_score:...
Rust
0
) else: self.assertListEqual( list(self_attentions[0].shape[-3:]), [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length], ) @slow @require_torch_gpu def test_torchscript_device_change(self): ...
Python
1
None => None, } } } impl<C: FamilyMember> FamilyStore for InnerComponentStore<C> { fn family(&self) -> Family { C::family() } } impl<C: FamilyMember> AnyComponentStore for InnerComponentStore<C> { fn remove(&mut self, entity: Entity) { if let Some(&id) = self.map.get...
Rust
0
rgs["next_run_time"] = datetime.now() scheduler.add_job( driver_pipeline, "interval", seconds=interval, args=[config, job_id], id=job_id, **kwargs, ) logging.info("Running driver pipeline every %d seconds (job %s).", interval, job_id) def _update_job( s...
Python
1
xt.image(src="/send.svg", width="1.5em", height="auto"), ), type_="submit", bg=styles.accent_dark, border_width="0px", rounded = "3xl" ...
Python
1
# Ultroid - UserBot # Copyright (C) 2021-2023 TeamUltroid # # This file is a part of < https://github.com/TeamUltroid/Ultroid/ > # PLease read the GNU Affero General Public License in # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>. import asyncio import os import random from random import shuffle ...
Python
1
chart_parameters(args): """Extracts and prepares chart parameters from the parsed arguments. Processes the command line arguments to create a dictionary of chart parameters, excluding any arguments that were not provided (i.e., are None). Args: args (argparse.Namespace): The parsed command lin...
Python
1
"SELECT {}, {}, {} FROM {} ORDER BY {} ASC", json_builder.id_field_name, json_builder.version_field_name, json_builder.data_field_name, qualified_table_name, json_builder.id_field_name, ), find_by_id_sql_query: format!( ...
Rust
0
current_breakpoint" in config assert "is_mobile" in config assert "is_tablet" in config assert "is_desktop" in config @patch("streamlit.set_page_config") @patch("src.ui.responsive.responsive_manager.apply_responsive_styles") @patch("src.ui.responsive.ResponsiveUtils.inject_screen_si...
Python
1
l { match *self { CCIER::_0 => false, CCIER::_1 => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> CCIER { match value { false => CCIER::_0, true => CCIER::_1, } } #[doc = "...
Rust
0
42: "C13", 43: "A14", 44: "B14", 45: "C11", # Shared with J600 47: "E13", }) ] # Extension for HUB75e 'hat' (marked "Huidu Hub75E-10 Support 1/32 ") hub75e = [ ("hub75_control", 0, # bank select (a, b, c, d, e) Subsignal("bank", Pins("J601:42 J601:41 ...
Python
1
""" User Management Models This module exports user management-related models. """ from app.models.user_management.preferences import UserPreference from app.models.user_management.user.user_management import UserProfile, UserOrganization, UserSession __all__ = [ 'UserPreference', 'UserProfile', 'UserOr...
Python
1
mentation // ----------------------------------- impl Context { pub fn shared_metadata(config: ScConfig) -> Arc<Self> { Arc::new(Self::new(config)) } /// private function to provision metadata fn new(config: ScConfig) -> Self { Self { spus: StoreContext::new(), ...
Rust
0
Query::new(terms))) } } } #[cfg(test)] pub mod tests { use super::*; use tantivy::schema::*; #[test] pub fn test_no_terms() { let body = r#"{ "phrase": { "test_u64": { "terms": [ ] } } }"#; let mut schema = SchemaBuilder::new(); schema.add_u64_field("test_u64", FAS...
Rust
0
) => { self.depth += magnitude }, CourseStep::Up(magnitude) => { self.depth -= magnitude }, } } } fn follow_with_aim(&mut self) { for step in &self.steps { match step { CourseStep::Forward(magnitude) => { self.horiz += m...
Rust
0
if data_path.endswith(".csv"): return self.execute(f"CREATE TEMP TABLE {table} AS SELECT * FROM read_csv_auto('{data_path}');") elif data_path.endswith(".json"): return self.execute(f"CREATE TEMP TABLE {table} AS SELECT * FROM read_json_auto('{data_path}');") else: ...
Python
1
from django.conf.urls import url from django.urls import include from rest_framework import routers from rest_framework_nested.routers import NestedSimpleRouter from api.siteapp.views.organizations import OrganizationViewSet from api.siteapp.views.portfolios import PortfolioViewSet from api.siteapp.views.projects impo...
Python
1
ase_msg_id") if base_id: try: await context.bot.edit_message_text( chat_id=chat_id, message_id=base_id, text=text, reply_markup=keyboard ) except BadRequest as e: ...
Python
1
g1 = torch.sigmoid(self.apperance_att_conv1(r2)) g1 = self.attn_mask_1(g1) gated1 = d2 * g1 d3 = self.avg_pooling_1(gated1) d4 = self.dropout_1(d3) r3 = self.avg_pooling_2(r2) r4 = self.dropout_2(r3) d4 = self.TSM_3(d4) d5 = torch.tanh(self.motion_con...
Python
1
mp profile #[derive(Clone, Eq, PartialEq, Debug, Hash, Serialize, Deserialize)] pub enum Profile { /// Default seccomp filter similar to docker's default profile #[serde(rename = "default")] Default, } /// Seccomp configuration #[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] #[serde(deny_unk...
Rust
0
licy-engine metrics. pub static METRICS_PREFIX: &str = "cincinnati_pe"; lazy_static! { static ref BUILD_INFO: Counter = Counter::with_opts(opts!( "build_info", "Build information", labels! { "git_commit" => match built_info::GIT_VERSION { Some(commit) => commit, ...
Rust
0
_channels=3, **kwargs): """Get 101 layers ResNeXt model with 32 groups of GPConv. Refer to the base class `models.ResNet` for more details. """ default_cfg = default_cfgs["resnext101_32x4d"] model_args = dict(block=Bottleneck, layers=[3, 4, 23, 3], groups=32, base_width=4, num_classes=num_classes, ...
Python
1
en used in the context of a transaction signature on the chain. pub type Signature = MultiSignature; /// Some way of identifying an account on the chain. We intentionally make it equivalent /// to the public key of our transaction signing scheme. pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>:...
Rust
0
import re from django.views import View from django.http import JsonResponse from django.views import View from MyModel.models import ReportCompetition class ReportRejectView(View): def post(self, request): # 获取 URL 路径 path = request.path # 解析 URL 路径 match = re.match(r'^/Teacher/rep...
Python
1
_api_app from airflow.api_fastapi.execution_api.deps import ( JWTBearerDep, JWTBearerTIPathDep, JWTRefresherDep, ) from airflow.api_fastapi.execution_api.routes.connections import has_connection_access from airflow.api_fasta...
Python
1
value = (row[0], row[1], row[2]) try: cur.execute(sql, value) conn.commit() except Exception as e: logger.error(e) cur.close() def execute_more_tasks(self, target): """ 协程池接收请求任务,可以扩展把解...
Python
1
{ self.case_sensitive = true; } pub fn limit(&mut self, limit: usize) { self.limit = limit } } #[salsa::query_group(SymbolsDatabaseStorage)] pub trait SymbolsDatabase: HirDatabase + SourceDatabaseExt + Upcast<dyn HirDatabase> { /// The symbol index for a given module. These modules sho...
Rust
0
te_ptr(rv, msgp).expect(ALLOC_FAIL_MSG); Message::from_ptr(msgp) } /// Create an empty message with a pre-allocated body buffer. /// /// The returned buffer will have a capacity equal to `cap` but a length of /// zero. To get a `Message` with a specified length, use `Message::zeros`. pub fn with_capacity(cap: ...
Rust
0
import torch import gymnasium as gym import numpy as np import time from stable_baselines3 import PPO from stable_baselines3.common.env_util import make_vec_env from stable_baselines3.common.logger import configure import time import src.environment_agent_rew import config.config_small_train as cfg vec_env = make_vec...
Python
1
Default for Struct__IO_FILE { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type _IO_FILE = Struct__IO_FILE; pub enum Struct__IO_FILE_plus { } pub type __io_read_fn = extern "C" fn(__cookie: *mut ::libc::c_void, __buf: *mut ::libc::c_char, __nbytes: size_t) -> __ssize_t; pub t...
Rust
0
16 } fn encode_value(self, encoder: &mut Encoder, context: Context) { MojomEncodable::encode(self.param0, encoder, context.clone()); } fn decode_value(decoder: &mut Decoder, context: Context) -> Result<Self, ValidationError> { let version = { let mut state = decoder.get_mut(...
Rust
0
import os.path from pyradise.fileio.series_info import SeriesInfo class TestSeriesInfo(SeriesInfo): def __init__(self, path): super().__init__(path) def update(self) -> None: pass def test_check__init__1(img_file_nii): tsi = TestSeriesInfo(img_file_nii) assert tsi.path == (img_file...
Python
1
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('inheritance', '0001_initial'), ('course', '0001_initial'), ] operations = [ migrations.CreateModel( name='LinkService', fields=[ ...
Python
1
} break (index, res); } }; let _ = rs.swap_remove(index); match res { Ok(res) => Ok(res), Err(e) => Err(Box::new(e)), } } } /// Selects the first active session. Receives from the selected session. /// Returns the received value...
Rust
0
let choose = get_input(); let num: usize = choose.parse().unwrap_or_default(); if !(0..choice.len()).contains(&num) { panic!("错误选项"); } return match num { 1 => lru::put_in, 0 | _ => fifo::put_in }; } fn handle_file_input() -> String { println!("{}", "请将文件拖拽至此处:".red()); ...
Rust
0
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/gui/impl/lobby/crew/tooltips/dismissed_toggle_tooltip.py from frameworks.wulf import ViewSettings from gui.impl.gen import R from gui.impl.gen.view_models.views.lobby.crew.tooltips.dismissed_toggle_tooltip_model import DismissedTogg...
Python
1
dx_ea), instruction!(MASK_OUT_X_EA, OP_ADD | WORD_SIZED | DEST_DX, Size::Word, "ADD", ea_all, decode_ea_dx, is_ea_dn, encode_ea_dx), instruction!(MASK_OUT_X_EA, OP_ADD | WORD_SIZED | DEST_EA, Size::Word, "ADD", ea_memory_alterable, decode_dx_ea, is_dn_ea, encode_dx_ea), instruction!(MASK_OUT_X_E...
Rust
0
&mut handle).is_err() { return -1; } I.subtype = PdfXObjectType::Image; } ImageType::Pdf => { if _opts.verbose != 0 { info!("[PDF]"); } let result: i32 = pdf_include_page(&mut I, handle, fullname, options); ...
Rust
0
match *self { EXTIPSEL4R::PORTA => 0, EXTIPSEL4R::PORTB => 1, EXTIPSEL4R::PORTC => 2, EXTIPSEL4R::PORTD => 3, EXTIPSEL4R::PORTE => 4, EXTIPSEL4R::PORTF => 5, EXTIPSEL4R::_Reserved(bits) => bits, } } #[allow(missin...
Rust
0
from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings from django.urls import reverse from django.core.exceptions import ValidationError class CustomUser(AbstractUser): age = models.PositiveIntegerField(blank=True, null=True) date_of_birth = models.D...
Python
1
PathBuf, } impl Default for NetworkConfig { fn default() -> NetworkConfig { NetworkConfig { peer_id: "".to_string(), role: "validator".to_string(), listen_address: "/ip4/0.0.0.0/tcp/6180".parse::<Multiaddr>().unwrap(), advertised_address: "/ip4/127.0.0.1/tcp...
Rust
0
!("unwrap called on {:?}", self) } } } fn p_lookfor(k: u64, a: &[u64], offset: u64) -> LookedUp { let n = a.len(); for pov in 0..n { let ii = ((k + pov as u64) % n as u64) as usize; // println!("looking in spot ii = {} with pov={}", ii, pov); if a[ii] == 0 { // p...
Rust
0
e super::regs::{setup_fpu, setup_msrs, setup_regs, setup_sregs}; use super::X8664arch; use super::{acpi, arch_memory_regions, bootparam, mptable, smbios}; use super::{ BOOT_STACK_POINTER, END_ADDR_BEFORE_32BITS, KERNEL_64BIT_ENTRY_OFFSET, KERNEL_START_OFFSET, PCIE_CFG_MMIO_SIZE, PCIE_CFG_MMIO_START, X86_64_SCI_...
Rust
0
.as_path().exists() { DirBuilder::new().recursive(true).create( store )?; } path_buf.push( file_name ); Ok ( path_buf ) }use std::error::Error; use std::fmt::Display; use crate::services::error::ServiceError; #[derive(Debug)] pub enum ControllerError { Unauthorized, Forbidden, NotFound...
Rust
0
rget=run_operations) operation_thread.start() # run_operations函数在新线程中执行操作序列,防止GUI冻结。 # total_steps获取操作序列的总步数,并设置进度条的最大值。 # for循环逐步执行操作序列,更新进度条。 # 使用try...except块捕获异常,确保程序在出错时不会崩溃。 # operation_thread启动一个新线程,执行run_operations函数。 def emergency_stop(self): self.serial_comm.send_comman...
Python
1
ackedTuple2, [A, B][C, D]); impl_for_tuple!(PackedTuple3, [A, B, C][D, E, F]); impl_for_tuple!(PackedTuple4, [A, B, C, D][E, F, G, H]); impl_for_tuple!(PackedTuple5, [A, B, C, D, E][F, G, H, I, J]); impl_for_tuple!(PackedTuple6, [A, B, C, D, E, F][G, H, I, J, K, L]); impl_for_tuple!(PackedTuple7, [A, B, C, D, E, F, G][...
Rust
0
[derive(Debug)] struct FileError { path: PathBuf, cause: io::Error, } impl fmt::Display for FileError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}: {}", self.path.display(), self.cause) } } impl std::error::Error for FileError {} // -- /// panics if chunks is too la...
Rust
0
def __add_or_edit_custom_word(self, data): try: wid = data.get("id") gid = data.get("gid") group_type = data.get("group_type") replaced = data.get("new_replaced") replace = data.get("new_replace") front = data.get("new_front") ...
Python
1
rd'], user.get('is_admin', False) ) for user in users] finally: close_db_connection(connection) @staticmethod def update_password(user_id, new_password): """ Update a user's password in the database. Args: user_id (int): The I...
Python
1