text
string
label_name
string
labels
int64
(0, 0), min_cluster_size, max_cluster_size, min_scaling_step, max_scaling_step, custom: Default::default(), }; tracing::info!(?context, "pushing test context..."); assert_ok!(flow.push_context(context).await); let event = &*assert_ok!(flow.recv_policy_event().awa...
Rust
0
next_nonce >> 17; next_nonce ^= next_nonce << 5; self.random_nonce = next_nonce.0; self.random_nonce } // Set the next alarm for this app using the period and provided start time. fn set_next_alarm<F: Frequency>(&mut self, now: u32) { self.alarm_data.t0 = now; let no...
Rust
0
from collections import namedtuple from urllib.request import urlretrieve import csv # this script retrieves a csv of UN population data and prints the countries with the highest absolute growth 1950-2015 # number of countries to list MAX_COUNTRIES = 10 # retrieves the csv Country = namedtuple('Country', 'population...
Python
1
1441) self.assertEqual(ts_result.aggregation_statistics, 'Average') # test for CV lookup tables # there should be 23 CV_VariableType records self.assertEqual(logical_file.metadata.cv_variable_types.all().count(), 23) # there should be 805 CV_VariableName records self.assertEqual(logical_file.m...
Python
1
STOP_WORDS = set( """ a abo ale ani dokelž hdyž jeli jelizo kaž pak potom tež tohodla zo zoby """.split() )
Python
1
pub _unk106: u8, pub _unk107: u8, pub collision_points: [u16; 0x4], pub death_timer: u16, pub defensive_matrix_dmg: u16, pub matrix_timer: u8, pub stim_timer: u8, pub ensnare_timer: u8, pub lockdown_timer: u8, pub irradiate_timer: u8, pub stasis_timer: u8, pub plague_tim...
Rust
0
in Clock or Pwm mode // // Param freq should be in range 4688Hz - 19.2MHz to prevent unexpected behavior, // however output frequency of Pwm pins can be further adjusted with SetDutyCycle. // So for smaller frequencies use Pwm pin with large cycle range. (Or implement custom software clock using output pin and sleep.) ...
Rust
0
"""auth: add refresh_token_expires_at Revision ID: 7fe1319250c5 Revises: 72a9b8f3f863 Create Date: 2025-10-02 10:50:21.169065 """ from collections.abc import Sequence from datetime import datetime, timedelta from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision: str = "7f...
Python
1
PageTableEntry::from_address(pdpt.address()), ) .unwrap(); asm::reload_cr3(); old_pml4e } use std::ffi::c_void; use crate::cvreturn::CVReturn; use crate::cvbase::{CVTimeStamp, CVOptionFlags}; use std::ops::{DerefMut, Deref}; use coregraphicsr::CGDirectDisplayID; ///Use pointers to this like ...
Rust
0
type Subscriber = Subscriber; type Error = core::convert::Infallible; fn start(self) -> Result<Self::Subscriber, Self::Error> { Ok(Subscriber::default()) } } /* SPDX-License-Identifier: MIT */ use zram_generator::{config, generator}; use anyhow::Result; use fs_extra::dir::{copy, CopyOptions}...
Rust
0
Get the user from the database :param db: Session: Get the database session from the dependency injection container :return: A streamingresponse object, which is a subclass of response :doc-author: Trelent """ image = await ImagesRepo(user, db).get_single(image_id) if image is None: rai...
Python
1
except RuntimeError: self.init_ui core.showWindow(self.window) core.window(self.window, edit=True, w=self.width, h=self.height) def close(self, value): """closes the UI""" core.deleteUI(self.window_name, window=True) ### learning Scene Version def set...
Python
1
let mut lu = LU { lu_size: lu_size, lu_nz: vec![S::zero(); lu_size], lu_row_ind: vec![0; lu_size], u_col_ptr: vec![0; ncol + 1], l_col_ptr: vec![0; ncol], row_perm: vec![0; nrow], col_perm: vec![0; ncol], n: n, }; let (mut rmatch, mut cmatch) = m...
Rust
0
forge_optional_xml_element(name: &str, content: Option<&String>) -> XMLElement { if content.is_some() { return forge_xml_element(name, content.unwrap().to_string()); } return XMLElement::new(name); } fn forge_url_element(name: &str, content: Option<&String>, node_type: &Nodetypes) -> XMLElement { ...
Rust
0
lf): m = Prophet() m.fit(self.__df) # Calculate the number of cutoff points(k) horizon = pd.Timedelta('4 days') period = pd.Timedelta('10 days') k = 5 df_cv = diagnostics.cross_validation( m, horizon='4 days', period='10 days', initial='90 days') ...
Python
1
pend(f"{str(key_l)}_{str(new_fid)}") i_min, j_min = closest_i_j(line_obj.xy, dict_of_line_objects[new_fid].xy) pp.create_switch(net, bus=line_obj.buses[i_min], element=dict_of_line_objects[new_fid].buses[j_min], ...
Python
1
ender_label("q_0", inits) != "" def test_cluster_gates(): """Test clustering gates""" pgates = [ ("MEASURE", "q_0"), ("GFF", "q_0", "q_1"), ("U1", "q_0", "q_2"), ("U1", "q_0", "q_3"), ("U1", "q_0", "q_4"), ("H", "q_1"), ("U1", "q_1", "q_2"), ("U1...
Python
1
[cfg_attr(test, assert_instr(vpcmpeqd))] #[stable(feature = "simd_x86", since = "1.27.0")] pub unsafe fn _mm256_cmpeq_epi32(a: __m256i, b: __m256i) -> __m256i { transmute::<i32x8, _>(simd_eq(a.as_i32x8(), b.as_i32x8())) } /// Compares packed 16-bit integers in `a` and `b` for equality. /// /// [Intel's documentati...
Rust
0
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pathSum(self, root: Optional[TreeNode], target: int) -> int: if root == None: return...
Python
1
().or_else(|| cache.prefix.clone()), version: self.backend.clone().or_else(|| cache.version.clone()), } } } <reponame>SyaOS/smeargle<gh_stars>0 mod locate; mod normalize; mod serve; mod state; use std::convert::TryFrom; use std::env; use async_std::path::PathBuf; use crate::locate::locate; us...
Rust
0
A period 2 oscillator that is the smallest and most common oscillator. #C www.conwaylife.com/wiki/index.php?title=Blinker x = 3, y = 1, rule = B3/S23 3o!").unwrap()) } pub fn get_r_pentomino() -> RuleLengthEncoded { RuleLengthEncoded::new_from_rle( Rle::new(r"#N R-pentomino #C A methuselah with lifespan 1...
Rust
0
# ============================================================================= # # Copyright (c) Kitware, Inc. # All rights reserved. # See LICENSE.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE....
Python
1
.step_adjustments .get(&num_decks) .copied() .unwrap_or_default(); if step_size == 0 || step_size > total_points { bail!( "Step size of {} must be between 5 and {}", step_size, total_points ...
Rust
0
MD_FORMAT_UNDERLINED: &str = "\u{e2bd}"; pub const MD_FORUM: &str = "\u{e2be}"; pub const MD_FORWARD: &str = "\u{e2c0}"; pub const MD_FORWARD_10: &str = "\u{e2c2}"; pub const MD_FORWARD_30: &str = "\u{e2c3}"; pub const MD_FORWARD_5: &str = "\u{e2c4}"; pub const MD_FREE_BREAKFAST: &str = "\u{e2c5}"; pub const MD_FULLSC...
Rust
0
s:%(process)d:%(name)s:%(levelname)s %(message)s") ) inner_logger.propagate = False parser = ArgumentParser() parser.add_arguments(TrainContext(), dest="context") args = parser.parse_args() context: TrainContext = args.context if not context.output_dir: current_time = datetime.now(...
Python
1
e_num && inode_num <= self.inode_count); unsafe { let inode = (Buffer::read(inode_num).get_data().as_ptr() as *const Inode).read(); INODES.assume_init_mut().insert(inode_num, Arc::new(inode)); Arc::clone(INODES.assume_init_ref().get(&inode_num).unwrap()) } } } pu...
Rust
0
write!(f, "[{}]", lane)?; } } Ok(()) } Self::SysReg(sr) => write!(f, "{}", sr), Self::MemReg(mr) => write!(f, "[{}]", mr), Self::MemPreIdx { reg, imm } => write!(f, "[{}, #{}]!", reg, imm), Self::MemPostIdxI...
Rust
0
class Solution: def destroyTargets(self, nums: List[int], space: int) -> int: count = collections.Counter([num % space for num in nums]) maxCount = max(count.values()) return min(num for num in nums if count[num % space] == maxCount)
Python
1
(GameMode::TKO, ctx, msg, args).await } #[command] #[description = "Display statistics of ctb user"] #[usage = "[username]"] #[example = "badewanne3"] #[aliases("ctb", "ctbprofile", "profilec")] pub async fn profilectb(ctx: &Context, msg: &Message, args: Args) -> CommandResult { profile_send(GameMode::CTB, ctx, ms...
Rust
0
# Copyright 2024-2025 IBM Corporation import pytest from aiu_trace_analyzer.pipeline.be_pair import AbstractHashQueueContext, EventPairDetectionContext # helper list to test input _event_list = [ {'name': 'eventA', 'ph': 'B', 'ts': 0, 'pid': 0}, {'name': 'eventA', 'ph': 'E', 'ts': 5, 'pid': 0}, ...
Python
1
REproduce".to_string())?; } self.seq_no += 1; if converter.convert(self.event_id(), &line, &mut msg).is_err() { // TODO: error handling for conversion failure report.skip(line.len()); } ...
Rust
0
} let xx = x_num / x_den; let yy = y * (y_num / y_den); self.e1.new_point(xx, yy) } } <gh_stars>1-10 use mq::{ camera::{set_camera, Camera2D}, color::{RED, WHITE}, math::Rect, }; use zgui as ui; mod common; #[derive(Clone, Copy, Debug)] enum Message { Command, } ...
Rust
0
ueError("step 不能为 0") except Exception as e: raise HTTPException(status_code=400, detail=f"范围参数错误: {e}") # 生成包含端点的范围 if step > 0: rng = range(start, end + 1, step) else: rng = range(start, end - 1, step) max_pages = 1000 count = len(list(rng)) if count > max_pages: ...
Python
1
his PKGBUILD was generated by `cargo aur`: https://crates.io/crates/cargo-aur" )?; writeln!(file)?; writeln!(file, "pkgname={}-bin", package.name)?; writeln!(file, "pkgver={}", package.version)?; writeln!(file, "pkgrel=1")?; writeln!(file, "pkgdesc=\"{}\"", package.description)?; writeln!(fi...
Rust
0
text = numsButton[x][y].textEntered.get() numsButton[x][y].textEntered.set(numsButton[newX][y].textEntered.get()) numsButton[newX][y].textEntered.set(text) checkWin() break for j in range(-1, 2): ne...
Python
1
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serialize(&self.0, serializer) } } impl<'de, T: Deserialize + ?Sized + 'static> serde::de::Deserialize<'de> for Arc<T> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'...
Rust
0
#!/usr/bin/env python3 # Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2 # This file is part of Checkmk (https://checkmk.com). It is subject to the terms and # conditions defined in the file COPYING, which is part of this source code package. from collections.abc import Mapping from cmk.agen...
Python
1
from datetime import datetime as DateTime, timezone as TimeZone import vampytest from ....utils import datetime_to_timestamp from ..fields import put_clip_created_at def _iter_options(): clip_created_at = DateTime(2016, 5, 14, tzinfo = TimeZone.utc) yield None, False, {} yield None, True, {'clip_c...
Python
1
pioResponse { let result = unsafe { gpioGetPWMrange(user_gpio) }; match result { BAD_USER_GPIO => Err("Bad user gpio".to_string()), _ => Ok(result as u32), } } /// Returns the real range used for the GPIO. /// /// If a hardware clock is active on the GPIO the reported real range will be 100...
Rust
0
1, i, dynamic.load_bias + dynamic.rela_read(i, "r_offset") + dynamic.rela_read(i, "r_addend"), ) if dynamic.has_jmprel: for i in range(dynamic.jmprel_entry_count()): if dynamic.jmprel_read(i, "...
Python
1
/ Don't rotate or mirror anything capabilities.current_transform, // Opaque window CompositeAlpha::Opaque, presentation_mode, // Don't really care FullscreenExclusive::Default, // Don't render parts of the viewport out of the screen ...
Rust
0
erver_name, &nameservers, WhatToFetch::Keys, format, sni); } _ => panic!("Unrecognized subcommand.") } } _ => panic!("Unrecognized subcommand.") } } <gh_stars>1-10 use wasm_bindgen::prelude::*; use parser::Parser; mod dic; mod parser; mod tokenizer; #[w...
Rust
0
err_msg=f"Local values mismatch when {case_info}.", ) def run_test_case_backward(self, test_case: SoftmaxGradTestCase): a = paddle.rand(test_case.input_shape, "float32") a.stop_gradient = False input_placements = [dist.Replicate() for _ in range(self.mesh.ndim)] inpu...
Python
1
) -> JsResult<JsFunction> { JsFunction::new(call.scope, add1) } pub fn call_js_function(call: Call) -> JsResult<JsNumber> { let scope = call.scope; let f = try!(try!(call.arguments.require(scope, 0)).check::<JsFunction>()); let args: Vec<Handle<JsNumber>> = vec![JsNumber::new(scope, 16.0)]; try!(f....
Rust
0
from fastapi import FastAPI, Depends, HTTPException from sqlalchemy.orm import Session import time from sqlalchemy.exc import OperationalError from app import database, models, schemas, redis_client import warnings warnings.filterwarnings('ignore') # MySQL bağlantısı hazır olana kadar bekle # bu bekleme olmadan f...
Python
1
dd\x11\x98\xc8\xb9\x1bS\ )woZ\xda\x04\x07\x80\xa8S\xff*\x08\x9c\x5cN\ S\xc0\x87z\xab\x05P\xeb\x16\xc7\xc4\xeec\x00\xee\x01\ 0=C\x80\xaf\xe2\xadP\xc0\xb7n\x09\xa8[<\xbd\ \xc2:\x82\xf6\x8f\x03@\x84m\xccd\x16\x03\xfa\x16\xeb\ \x8e\xa0\x04\xf2\xa5\x5c\xb9|\x87u\x87kbz\xb7\x1c\ \xc7\xf7\xd4T\x83\xa5\xd2VO\xf4\x9f\xac;\x82\x...
Python
1
None] UC_HOOK_CALLBACK_TYPE = Union[ UC_HOOK_CODE_TYPE, UC_HOOK_INSN_INVALID_TYPE, UC_HOOK_MEM_INVALID_TYPE, UC_HOOK_MEM_ACCESS_TYPE, UC_HOOK_INSN_IN_TYPE, UC_HOOK_INSN_OUT_TYPE, UC_HOOK_INSN_SYSCALL_TYPE, UC_HOOK_INSN_SYS_TYPE, UC_HOOK_INSN_CPUID_TYPE, UC_HOOK_EDGE_GEN_TYP...
Python
1
r (i, asteroid) in self.asteriods.iter_mut().enumerate() { match self.map.check_collision(bullet, asteroid) { None => continue, Some(collision_position) => { collision_result = asteroid.process_collision(&collision_position, &self.map); ...
Rust
0
a non-rooted path. //! //! If the result of this process is an empty string, return the string `"."`, representing the current directory. //! //! It performs this transform lexically, without touching the filesystem. Therefore it doesn't do //! any symlink resolution or absolute path resolution. For more information yo...
Rust
0
from django.urls import path,include from . views import * urlpatterns = [ path('get-tasks/<str:id>/',display_tasks,name='get_tasks'), path('post-task',post_task,name='post_task'), path('change-task/<str:id>/',change_task,name='change_task'), ]
Python
1
import numpy as np import cv2 def zmMinFilterGray(src, r=5): '''最小值滤波,r是滤波器半径''' return cv2.erode(src, np.ones((2 * r + 1, 2 * r + 1))) # 使用opencv的erode函数更高效 def guidedfilter(I, p, r, eps): '''引导滤波,直接参考网上的matlab代码''' height, width = I.shape m_I = cv2.boxFilter(I, -1, (r, r)) m_p = cv2.boxFil...
Python
1
from dataclasses import dataclass, field import tyro import numpy as np import jax.numpy as jnp import navix as nx from navix import observations from navix.agents import PPO, PPOHparams, ActorCritic from navix.environments.environment import Environment # set persistent compilation cache directory # jax.config.update...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import re import time from colorama import Fore, init # Initialize colorama init(autoreset=True) # Links YOUTUBE_LINK = "https://youtube.com/@hackers_colony_tech?si=pvdCWZggTIuGb0ya" BGMI_SUPPORT_LINK = "https://bgmi.krafton.com/en/support" # Countdown helper...
Python
1
| j||d|d8}qWqkW|j| ||7}||7}q4W|j qhndGHdS(Ntrbsopen file erroriiBiiMs file errori iiiiiii iiiiis(dont support this bitmap file format yet( topent bytearraytreadtc...
Python
1
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_jwt_extended import JWTManager from api.endpoints import bp from dotenv import load_dotenv import os # Carregar as variáveis de ambiente do arquivo .env.api load_dotenv('.env.api') db = SQLAlchemy() jwt = JWTManager() def create_app(): ap...
Python
1
, 12, 5, 2]; let target = 9; let sg = SubsetGenerator::new(&set, false); let mut found = false; for subset in sg.into_iter() { let sum = subset.into_iter().fold(0, |acc, i| acc + *i); if sum == target { found = true; break; } } println!("{:}", fo...
Rust
0
错误原因:{str(e)}") def _save_raw_image(self, image, save_path): """保存RAW格式图像(内部方法)""" if len(image.shape) != 2: raise ValueError("只能保存灰度图为RAW格式") with open(save_path, 'wb') as f: height, width = image.shape f.write(struct.pack('II', width, h...
Python
1
if patch_dict['owner'] == pkg_fullname: remove.append(fullname) for fullname in remove: package_to_patch.pop(fullname) if not package_to_patch: empty.append(sha256) # remove any entries that are now empty for sha256 i...
Python
1
""" Script to update API and restart uvicorn server. This script will: 1. Generate models using datamodel-code-generator 2. Check routes directory 3. Restart uvicorn server """ import subprocess import os import time def update_api(): print("🔹 Step 1: Generating models") try: result = subprocess.run([...
Python
1
word_parameters : PasswordParameters, pub password_salt : PasswordSalt, pub token_identifier : TokenIdentifier, pub token_description : TokenDescription, pub token_encrypted : TokenDataEncrypted, pub authentication_only_token : AuthenticationTagOnlyToken, pub authentication_with_data : AuthenticationTagWithData, ...
Rust
0
// y axis Constant(None), HelloState::show_y_tick_labels, HelloState::show_y_axis, HelloState::monica.then(MonicaData::systm), )), 2.,...
Rust
0
rouped_findings = {} for finding in findings: path = finding["path"] if path not in grouped_findings: grouped_findings[path] = { "path": path, "scanned_code": f...
Python
1
# -*- coding: utf-8 -*- # Copyright (c) 2016 Ericsson AB # # 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/licenses/LICENSE-2.0 # # Unless required by applicable ...
Python
1
](canec::R) reader structure"] impl crate::Readable for CANEC {} #[doc = "Error counter"] pub mod canec; #[doc = "Bit timing register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write...
Rust
0
dispatcher.utter_message(text="I'm not sure which link you're referring to. Please be more specific.") else: dispatcher.utter_message(text="Please specify which link you're looking for.") return [] ''' class ActionProvideLink(Action): def name(self) -> str: retu...
Python
1
, * which encode all local IP addresses for the other side to find us. */ DirectTcpV1, /** * UNSTABLE; NOT IMPLEMENTED! * Try to connect directly to the other side via UDT. * * This supersedes [`Ability::DirectTcpV1`] because it has several advantages: * * - Works with st...
Rust
0
NONE: crate::ctypes::c_int = 0; pub const PICO_ERROR_TIMEOUT: crate::ctypes::c_int = -1; pub const PICO_ERROR_GENERIC: crate::ctypes::c_int = -2; pub const PICO_ERROR_NO_DATA: crate::ctypes::c_int = -3; #[doc = " Common return codes from pico_sdk methods that return a status"] pub type _bindgen_ty_1 = crate::ctypes::c_...
Rust
0
order=3, order_z=0) properties['shape_after_resample'] = new_shape return data, properties def preprocess(self, data, properties, crop_first=True): from light_training.process_framework.norm import norm_func ...
Python
1
import sys import os sys.path.append(os.path.dirname(__file__)) # for pytest from common import wrap, unwrap def test_wrap(): test_string = """\ Now is the time for all good men to come to the aid of their country. This is indented by 3 spaces. What follows is more of the same. Now is the time for all good men...
Python
1
import typing import flask import marshmallow as ma if typing.TYPE_CHECKING: from flask.wrappers import Response class Schema(ma.Schema): """Base serializer with which to define custom serializers. See `marshmallow.Schema` for more details about the `Schema` API. """ def jsonify( self,...
Python
1
# Utility for input debugging. import InputData inData = InputData.instance import DebugUtils NOTIFY_CODES = { 0 : "Click", 1 : "Double Click", 2 : "Focus", 3 : "Unfocus", 4 : "Mouse Enter", 5 : "Mouse Leave", 6 : "Character", 7 : "Scroll Up", 8 : "Scroll Down", 9 : "New Horizontal Stop", 10 : "New Vertical...
Python
1
# -*- coding: utf-8 -*- # vim:fenc=utf-8 ''' Benchmark loader modified to allow live data streaming ------------------------------------------------------ :copyright (c) 2014 Xavier Bruhiere. :license: Apache2.0, see LICENSE for more details. ''' from datetime import datetime import pandas as pd from collec...
Python
1
TODO: There's probably a better way to do this #[path = "universe.rs"] mod universe; #[path = "web_sys_mixins.rs"] mod web_sys_mixins; use wasm_bindgen::JsCast; extern crate web_sys; use web_sys::CanvasRenderingContext2d; use web_sys::Element; use web_sys::HtmlCanvasElement; use web_sys::HtmlElement; use web_sys::Htm...
Rust
0
insicCall, weights::{DispatchInfo, GetDispatchInfo}, }; use scale_info::TypeInfo; use sp_runtime::{ traits::{ self, Checkable, Extrinsic, ExtrinsicMetadata, IdentifyAccount, MaybeDisplay, Member, SignedExtension, }, transaction_validity::{InvalidTransaction, TransactionValidityError}, RuntimeDebug, }; /// A e...
Rust
0
#[serde(rename = "41070")] pub delivery_stream_importer_of_record: Option<String>, /// DeliveryStreamNegativeTolerance #[serde(skip_serializing_if = "Option::is_none")] #[serde(deserialize_with = "fix_common::workarounds::from_opt_str")]// https://github.com/serde-rs/serde/issues/1183 #[serde(default)] #[serde(...
Rust
0
""" battle of two armies """ import magent def get_config(map_size): gw = magent.gridworld cfg = gw.Config() cfg.set({"map_width": map_size, "map_height": map_size}) cfg.set({"minimap_mode": True}) cfg.set({"embedding_size": 10}) small = cfg.register_agent_type( "small", {'w...
Python
1
) , "::" , stringify ! ( RaiseTPL ) )); assert_eq! (unsafe { & ( * ( 0 as * const _EFI_BOOT_SERVICES ) ) . RestoreTPL as * const _ as usize } , 32usize , concat ! ( "Alignment of field: " , stringify ! ( _EFI_BOOT_SERVICES ) , "::" , st...
Rust
0
} } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> { self.project().inner.poll_flush(cx) } fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> { self.project().inner.poll_shutdown(cx) } } impl<F: AsyncSeek + Unpin> As...
Rust
0
<< 24) Chain mode send_ring[i].desc1 |= (1 << 24); send_ring[i].desc2 = buffer_page_pa as u32; if (i + 1) == send_ring.len() { send_ring[i].desc3 = virt_to_phys(&send_ring[0] as *const dma_desc as usize) as u32; } else { send_ring[i].des...
Rust
0
Session = CommandCodeStructure::START_AUTH_SESSION.0, VerifySignature = CommandCodeStructure::VERIFY_SIGNATURE.0, EccParameters = CommandCodeStructure::ECC_PARAMETERS.0, FirmwareRead = CommandCodeStructure::FIRMWARE_READ.0, GetCapability = CommandCodeStructure::GET_CAPABILITY.0, GetRandom = CommandC...
Rust
0
se str(self.count) self.watermark_non_member_str = "" if args.watermark_non_member else "only_member_" self.split_str = f"split_{args.split}_" if args.split > 0 else "" self.no_member_str = "no_member_" if args.mode in ["BookMIA", "Arxiv"] else "" self.suffix = f"syn_{args.synonym_method...
Python
1
s_some() } // Param is passed by value, moved pub fn set_origin_id(&mut self, v: u64) { self.origin_id = ::std::option::Option::Some(v); } pub fn get_origin_id(&self) -> u64 { self.origin_id.unwrap_or(0) } fn get_origin_id_for_reflect(&self) -> &::std::option::Option<u64> ...
Rust
0
"""Adds heartbeat_interval_seconds column to worker table Revision ID: c2d001b7dd06 Revises: 5b0bd3b41a23 Create Date: 2023-09-06 08:47:29.381718 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "c2d001b7dd06" down_revision = "5b0bd3b41a23" branch_labels = None d...
Python
1
printed, 0, f) } } //! # Map //! //! This module contains structures that correspond to the map API responses //! //! [API documentation here](https://docs.beatsaver.com/responses/beatmap.html) use crate::BeatSaverUser; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; /// This structure specifies wh...
Rust
0
"# ); Ok(()) } #[test] fn page_preprocess_include_anchor() -> Result<()> { let temp_dir = tempfile::tempdir()?; let root_dir = temp_dir.path().to_path_buf(); fs::create_dir_all(root_dir.join("src"))?; let page_path = root_dir.join("src").join("page.md"); ...
Rust
0
fn expected_function() -> Res { Err("not a function".to_string()) } pub(crate) fn missing_function() -> Res { Err("function implementation is missing".to_string()) } fn car(pair: &Obj) -> &Obj { &pair.downcast_ref::<Pair>().unwrap().0 } fn cdr(pair: &Obj) -> &Obj { &pair.downcast_ref::<Pair>().unwra...
Rust
0
import _plotly_utils.basevalidators class FamilysrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="familysrc", parent_name="icicle.insidetextfont", **kwargs ): super(FamilysrcValidator, self).__init__( plotly_name=plotly_name, pare...
Python
1
e=root_certificate.dn.organizationName, ) certificate = CertificateFactory( type=CertificateTypes.INTERMEDIATE, name="test_certificate_passphrase_wrong_cert_passphrase", parent=root_certificate, dn=subject, ) certhandler = Certificate() ...
Python
1
//! lines. //! //! We use a specific version of PLRU: BPLRU or bit PLRU. Tree PLRU is an alternative, but it is //! not easy to make concurrent. //! //! # Usage //! //! ## Runtime defined number of cache lines //! //! This can be achieved through `plru::create()` unless the `no_std` feature is enabled. //! //! ## How ...
Rust
0
from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler from sklearn.tree import DecisionTreeClassifier, export_text from src.models import Submission from src.config.database import db def kmeans(quiz_id): submissions = Submission.query.filter_by(quiz_id=quiz_id).all() if not subm...
Python
1
# Copyright cocotb contributors # Licensed under the Revised BSD License, see LICENSE for details. # SPDX-License-Identifier: BSD-3-Clause from typing import Union import cocotb cocotb_2x_or_newer = cocotb.__version__.startswith("2") if cocotb_2x_or_newer: from cocotb.types import Logic, LogicArray, Range ...
Python
1
import os from string import Template from typing import List, Dict import torch.cuda from transformers import AutoTokenizer, AutoModelForCausalLM from ChatHaruhi.response_GLM_local import pretrained_model_download from ChatHaruhi.response_Gemma_2b import message2query4Gemma aclient = None client = None tokenizer ...
Python
1
NativeEventOperation { match self { ButtonHook::Hotkey(hook) => hook.native_event_operation, ButtonHook::Remap(_) => NativeEventOperation::Block, } } fn run(&self, event: ButtonEvent) { match self { ButtonHook::Hotkey(hook) => hook.process.run(event)...
Rust
0
progress_bar.empty() with col2: st.header("📊 Analysis Status") if hasattr(st.session_state, 'explanation_complete') and st.session_state.explanation_complete: result = st.session_state.explanation_result # Analysis metrics col_a, c...
Python
1
password(): """Get the password from session state""" # This will be set when user authenticates return st.session_state.get('user_password', '') # Function to auto-play audio from URL def autoplay_audio_url(url): try: response = requests.get(url) audio_bytes = response.content ...
Python
1
}) .max_by_key(|zone| zone.name().len()) .ok_or_else(|| format_err!("could not find authoritative DNS zone for: {}", name)) } } pub trait DnsZone: fmt::Debug { fn id(&self) -> &str; fn name(&self) -> &str; fn bind(&self, fqdn: &str, target: DnsTarget) -> Result<(), Error>; ...
Rust
0
"mkdir_test5/mkdir_test5_1"; #[test] fn test_mkdir_mkdir() { let (_, mut ucmd) = testing(UTIL_NAME); let exit_success = ucmd.arg(TEST_DIR1).run().success; assert_eq!(exit_success, true); } #[test] fn test_mkdir_dup_dir() { let ts = TestSet::new(UTIL_NAME); let exit_success = ts.util_cmd().arg(TE...
Rust
0
if key == ord(config.get('controls','contrast+')): contrast = vid.get(cv2.CAP_PROP_CONTRAST) vid.set(cv2.CAP_PROP_CONTRAST, contrast+5) contrast = vid.get(cv2.CAP_PROP_CONTRAST) print("CONTRAST: " + str(contrast)) #add page if key == int(confi...
Python
1
get_as_author_custom( header_hashed: &HeaderHashed, ribosome: &impl RibosomeT, network: &HolochainP2pCell, workspace_lock: CallZomeWorkspaceLock, ) -> RibosomeResult<Option<ValidationPackageResult>> { let header = header_hashed.as_content(); let access = ValidationPackageHostAccess::new(workspa...
Rust
0
elf(A::zero(), B::zero()) } fn is_zero(&self) -> bool { self.0.is_zero() && self.1.is_zero() } } impl<A, B> Mul for ChainData<A, B> where A: Mul, B: Mul, { type Output = ChainData<A::Output, B::Output>; fn mul(self, rhs: Self) -> Self::Output { ChainData(self.0 * rhs.0, se...
Rust
0