text
string
label_name
string
labels
int64
wait_when_err=wait_when_err, ) sys.stderr.write("\n") # install qlib sys.stderr.write("Installing qlib...\n") execute(f"{python_path} -m pip install --upgrade pip", wait_when_err=wait_when_err) # TODO: FIX ME! execute(...
Python
1
,non_camel_case_types,unused_imports,non_snake_case)] use vpp_api_macros::{VppMessage,VppUnionIdent}; use std::convert::TryInto; use serde::{de::DeserializeOwned, Deserialize, Serialize}; pub use vpp_api_encoding::typ::*; pub use vpp_api_encoding; use vpp_api_message::VppApiMessage; use serde_repr::{Serialize_repr, D...
Rust
0
rint("Given the values 6 and 4") print("sum=",6+4,"/ndifference=",6-4,"/nproduct=",6*4)
Python
1
_and(image_idx, torch.logical_and(cumsum_idx > 0, cumsum_idx <= num_img_token)) text_embeds[target_idx] = self.project_up(target_image_embeds).to(text_embeds.device) outputs = self.model.decoder.lm.model( inputs_embeds=text_embeds, attention_mask=attention_ma...
Python
1
HeaderValue>>, BoxError> { self.trailers() } fn make_new(&self) -> Box<dyn BodyCallback> { Box::new(Sha256Callback::default()) } } #[cfg(test)] mod tests { use super::{ Crc32cCallback, Crc32callback, Sha1Callback, Sha256Callback, CRC_32_C_NAME, CRC_32_NAME, SHA_1_NAME, ...
Rust
0
""" Created on Wed Dec 18 2019 @author: RosemaryHe """ import pandas as pd import numpy as np import math import statsmodels.api as sm from numpy import linalg as la ##calculate risk covariance matrix F and specific risk matrix Delta def half_life(time, length): sum = 0 for i in range(length): sum +=...
Python
1
// Stop fuzzing if we are not inserting datoms. This prevents // the fuzzer from focussing too much on doing insert all the // time, without inserting datoms. This line speeds up the // fuzzer by roughly 10x. if datoms.len() == 0 { return N...
Rust
0
!(res.is_err()); assert_eq!(res.unwrap_err().kind(), io::ErrorKind::Other); // Try cloning the socket and registering it again let socket2 = socket.try_clone().unwrap(); let res = poll2.registry().register( &socket2, Token(0), Interests::READABLE | Interests::WRITABLE, ); ...
Rust
0
{ /// #[ink(constructor)] /// pub fn new() -> Self { /// Self::default() /// } /// /// #[ink(message)] /// #[brush::modifiers(once)] /// pub fn init(&mut self, owner: AccountId) { /// self.owner = owner; /// } /// } /// } /// ``` #[proc...
Rust
0
# encoding: utf-8 from app.libs.snow import IdWorker from app.models import Base from exit import db class Company(Base): __tablename__ = 'company' __table_args__ = ({'comment': '307 公司信息表'}) cname = db.Column(db.String(20), comment='公司的名字') uId = db.Column(db.BigInteger, comment='关联的用户id') cplace...
Python
1
# coding: utf-8 # Copyright (C) 2014 by Ronnie Sahlberg <ronniesahlberg@gmail.com> # Copyright (C) 2015 by Markus Rosjat <markus.rosjat@gmail.com> # SPDX-FileCopyrightText: 2014 The python-scsi Authors # # SPDX-License-Identifier: LGPL-2.1-or-later import unittest from pyscsi.pyscsi.scsi_cdb_initelementstatuswithran...
Python
1
elf> { match value.version() { 1 => Ok(unsafe { value.v1.body.data.key.usage }), _ => Err(ErrorKind::InvalidInput.into()), } } } impl TryFrom<&Certificate> for crate::certs::Usage { type Error = Error; fn try_from(value: &Certificate) -> Result<Self> { Ok(Us...
Rust
0
osition::Match(tok.clone(), *occ, Direction::End)); } } } } } set } } #[cfg(test)] mod tests { use super::super::token::Token; use super::*; use crate::StringProgram; #[test] fn generate_substring_set() { ...
Rust
0
# Copyright 2024 Davide Gessa # 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 law or agreed to in writing, softwa...
Python
1
'), "+ +"), "+",); assert_eq!(parse_ok(punct('+'), "++"), "+",); } #[test] fn test_delim() { assert_eq!(parse_ok(group(Delimiter::Bracket, ident()), "[foo]"), "foo",); assert_eq!(parse_ok(group(Delimiter::Brace, ident()), "{foo}"), "foo",); assert_eq!( parse_ok(group(Delimiter::Parenthesis, ide...
Rust
0
from dvc.cli import formatter from dvc.cli.command import CmdBase from dvc.cli.utils import append_doc_link from dvc.compare import TabularData from dvc.log import logger from dvc.ui import ui logger = logger.getChild(__name__) class CmdQueueStatus(CmdBase): """Show queue task and worker status.""" def run(...
Python
1
if idx in label_dict.keys(): label_dict[idx] += bin[idx] else : label_dict[idx] = bin[idx] if len(no_use) == 3: train_check = False ...
Python
1
s); (offs, next_offs - offs) } fn set_u16(&mut self, offs: usize, data: u16) { self.copy(offs, &data.to_be_bytes()); } fn set_u32(&mut self, offs: usize, data: u32) { self.copy(offs, &data.to_be_bytes()); } fn get_u16(&self, offs: usize) -> u16 { u16::from_be_b...
Rust
0
Default::default()); let (send_results, results) = channel(); dbg!(case.description); let mut deps = case.plan.dependencies(); let plan = case.plan.clone(); dbg!(&plan); for tx in case.transactions.iter() { for datum in tx { ...
Rust
0
es", default=4, help="PCIe lanes: 4 (default), 8 or 16") args = parser.parse_args() platform = sqrl_xcu1525.Platform() soc = LitePCIeSoC(platform, speed=args.speed, nlanes=int(args.nlanes)) builder = Builder(soc, output_dir="build/xcu1525", csr_csv="csr.csv") builder.build(build_nam...
Python
1
def bubblesort(list): # Swap the elements to arrange in order for iter_num in range(len(list) - 1, 0, -1): for idx in range(iter_num): if list[idx] > list[idx + 1]: temp = list[idx] list[idx] = list[idx + 1] list[idx + 1] = temp list = [19, ...
Python
1
Cow; use crc::{Algorithm, Crc, CRC_16_IBM_3740}; pub(crate) const CRC_ALGO: Algorithm<u16> = CRC_16_IBM_3740; pub fn calculate_crc16(complete_pix: &str) -> u16 { let crc = Crc::<u16>::new(&CRC_ALGO); let mut digest = crc.digest(); digest.update(complete_pix.as_bytes()); digest.finalize() } pub fn f...
Rust
0
, else it /// can be `tombstoned` after `deposit / RentPerBlock `. Accounts may deposit more funds to /// keep the vault alive. /// /// # Emits /// - [`Event::VaultCreated`](Event::VaultCreated) /// /// # Errors /// - When the origin is not signed. /// - When `deposit < CreationDeposit`. /// - O...
Rust
0
#!/usr/bin/env pytest import htcondor2 import logging from getpass import getuser from ornithology import * logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) @action def the_condor(default_condor): return default_condor @action def the_held_test_job(the_condor, path_to_sleep, test_dir): ...
Python
1
######################################################################## # File name: rpc.py # This file is part of: aioxmpp # # LICENSE # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, ...
Python
1
t(format_args!("show errors {}{}", id, error_type_str)) } <gh_stars>100-1000 /* * Copyright 2021 Fluence Labs Limited * * 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...
Rust
0
int "%s Expected transcript: %s%s" % (ENDC, OKBLUE, str(expected)) print "%s Observed transcript: %s%s" % (ENDC, OKBLUE, str(actual)) for i, (act, just) in enumerate(zip(actual, justification)): print "%s %d: Ran %s%s%s because: %s" \ % (ENDC, i+1, OKBLUE, act, ENDC, just...
Python
1
ser_data, context) results.append( {"user_id": user_data.user_id, "insight": insight} ) self.logger.debug( "Successfully analyzed user %s", user_data.user_id ) except Exception as e: sel...
Python
1
("This can't be empty"))?; let op_order = OpOrder::new(op_type, header.timestamp()); let timestamp = header.timestamp(); let visibility = header.entry_type().map(|et| *et.visibility()); // Put the header back by value. let dependency = get_dependency(op_type, ...
Rust
0
f agent_page(agent_name: str, username: str = Depends(auth)): from pathlib import Path # Get the absolute path to the project root project_root = Path(__file__).parent.parent page_path = project_root / "app" / "agents" / agent_name / "page.html" if not page_path.exists(): raise HTTPExce...
Python
1
with buttons_placeholder: cols = st.columns([0.15, 1]) cols[0].button("Regenerate Response", key="regenerate", on_click=st.session_state.agent.regenerate_response) cols[-1].button("Clear Chat", key="clear", ...
Python
1
64G64B64_SINT, bdim: (1, 1), size: Some(24), ty: Sint}, R64G64B64Sfloat => {vk: FORMAT_R64G64B64_SFLOAT, bdim: (1, 1), size: Some(24), ty: Float}, R64G64B64A64Uint => {vk: FORMAT_R64G64B64A64_UINT, bdim: (1, 1), size: Some(32), ty: Uint}, R64G64B64A64Sint => {vk: FORMAT_R64G64B64A64_SINT, bdim: (1, 1), size...
Rust
0
not included in the regex crate. Thus, if // pathname contains it, it will fail on converting &[u8] to // string. static ref RE: regex::Regex = regex::Regex::new(r#"[\p{Control}\p{Format}\p{PrivateUse}\p{Unassigned}]"#).unwrap(); } RE.replace_all(v, "?") } pub(crate) struct Record { ...
Rust
0
# -*- coding: utf-8 -*- # File generated from our OpenAPI spec from stripe._refund import Refund from stripe._request_options import RequestOptions from stripe._stripe_service import StripeService from stripe._util import sanitize_id from typing import List, cast from typing_extensions import NotRequired, TypedDict c...
Python
1
; pub const SYS_REMOVEXATTR: u32 = 197; pub const SYS_LREMOVEXATTR: u32 = 198; pub const SYS_FREMOVEXATTR: u32 = 199; pub const SYS_TKILL: u32 = 200; pub const SYS_TIME: u32 = 201; pub const SYS_FUTEX: u32 = 202; pub const SYS_SCHED_SETAFFINITY: u32 = 203; pub const SYS_SCHED_GETAFFINITY: u32 = 204; pub const SYS_SET_T...
Rust
0
Hint(AObj: usize) -> bool; pub fn Memo_SetShowHint(AObj: usize, AValue: bool); pub fn Memo_GetTabOrder(AObj: usize) -> TTabOrder; pub fn Memo_SetTabOrder(AObj: usize, AValue: TTabOrder); pub fn Memo_GetTabStop(AObj: usize) -> bool; pub fn Memo_SetTabStop(AObj: usize, AValue: bool); pub fn Memo_GetVisible(AO...
Rust
0
0 => Ok(ConnectReturnCode::Accepted), 1 => Ok(ConnectReturnCode::RefusedProtocolVersion), 2 => Ok(ConnectReturnCode::RefusedIdentifierRejected), 3 => Ok(ConnectReturnCode::ServerUnavailable), 4 => Ok(ConnectReturnCode::BadUsernamePassword), 5 => Ok(Con...
Rust
0
ocket; const BUFSIZE: usize = 2048; fn do_(socket: UdpSocket, addr: SocketAddr) { let mut buf = [0; BUFSIZE]; socket.send_to(&browse_protocol::request_list_6(), addr).unwrap(); loop { let (len, from) = socket.recv_from(&mut buf).unwrap(); if from != addr { error!("received re...
Rust
0
##################### # 위치 중요 hist_values = hist_values * np.diff(bin_edges) # print("Sum: ", hist_values.sum()) prob_density = util.get_hist_data(tensor_np, hist_values, bin_edges) ################################ if "mahalanobis" in cfgs.CURRENT_LABEL: h...
Python
1
dgetItem(json.loads(response)['Instances']['Instance'][i]['InstanceId']) RegionId = QTableWidgetItem(RegionIds[json.loads(response)['Instances']['Instance'][i]['RegionId']]) HostName = QTableWidgetItem(json.loads(response)['Instances']['Instance'][i]['HostName']) OSName =...
Python
1
amespace="namespace1", data={"text": "This is the text", "id": "1"}, emitted_at=1234, ), DestinationSyncMode.append_dedup, True, False, "namespace1_stream1_1", id="update", ), pytest.param( ...
Python
1
l_itr as f64) / total_time); break; } } } best_time } fn bench_x25519_shared_key(name: bool, _: usize) -> String { if name { return "X25519 Shared Key: ".to_string(); } let secret_key = X25519SecretKey::new(); let public_key = X25519SecretKey::new()...
Rust
0
/// NULL NULL 2 /// (drained) fn make_src_executor_using_fixture_2() -> MockExecutor { MockExecutor::new( vec![ FieldTypeTp::LongLong.into(), FieldTypeTp::LongLong.into(), FieldTypeTp::LongLong.into(), ], ...
Rust
0
# random_state=m) # cv=10即10折交叉验证 # krr_poly.fit(x_train, y_train) # 对给定数据集选取最佳参数 # if krr_poly.best_score_>bestscore: # bestscore = krr_poly.best_score_ # model = krr_poly.best_est...
Python
1
") } if read & 0b10000000 == 0 { break; } } (result, num_read) } fn get_var_i32_limit(&mut self, max_size: u32) -> Option<(i32, i32)> { let mut num_read = 0i32; let mut result = 0i32; let mut read; while num_rea...
Rust
0
10,30,3072] return objs class ObjectLayoutEncoder_noFourier(nn.Module): def __init__(self, in_dim, out_dim): super().__init__() self.in_dim = in_dim self.out_dim = out_dim self.linears = PixArtAlphaTextProjection(in_features=self.in_dim,hidden_size=out_dim//2,o...
Python
1
.current_chunk].split_at(self.current_pos); if target.len() > 0 { let count = target.len().min(chunk.len()); size += target.write(&chunk[0..count])?; if count == chunk.len() { self.current_chunk += 1; ...
Rust
0
arch = "aarch64")] writer.put_b_label(after_report_impl); self.current_report_impl = writer.pc(); #[cfg(unix)] writer.put_bytes(self.blob_report()); writer.put_label(after_report_impl); } //writer.put_brk_imm(1); // Preserve x0, x1:...
Rust
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'France - VAT Anti-Fraud Certification for Point of Sale (CGI 286 I-3 bis)', 'version': '1.0', 'category': 'Accounting/Localizations/Point of Sale', 'description': """ This add-on brings the tec...
Python
1
3, 4, 5, 6, 7]); let hex8_mesh = Mesh3d::from_vertices_and_connectivity(vertices.clone(), vec![hex8]); let hex27_mesh = Hex27Mesh::from(&hex8_mesh); let hex27_connectivity = hex27_mesh.connectivity().first().unwrap(); assert_eq!(hex27_connectivity.0[0..8], [0, 1, 2, 3, 4, 5, 6, 7]); // assert_eq!...
Rust
0
.e_peak, np.nan * u.TeV) def test_vectorized_integrate_spectrum(): model = PowerLawSpectralModel() parameter_samples = [np.ones(10) * par.quantity for par in model.parameters] energy = [100, 1000, 10000] * u.GeV integral = integrate_spectrum(model, energy[:-1], energy[1:], ndecade=20) vector_in...
Python
1
import requests, json, termcolor # "@workspace definition of DeltaDeltaChatStreamer\n" + initial_messages = [ {"role": "user", "content": "@definition DeltaDeltaChatStreamer\n" + "@local-notes-to-self\n" + "hello world" }, ] def ask_chat(messages): response = requests.post( "http://127.0.0.1:...
Python
1
port = 443 else: port = int(port) self.connection_data = {"aws_access_key_id": aws_access, "aws_secret_access_key": aws_secret, "is_secure": purl.scheme == "https", "validate_certs": not insecu...
Python
1
りの2画面は、画面1と2のミラーとなる。 // (マッパーによっては4画面分のROMを持つカセットもある。) // ネームテーブルは、メモリ常に「左上 -> 右上 -> 左下 -> 右下」の順に配置されている。 // ・左上:$2000-$23FF // ・右上:$2400-$27FF // ・左下:$2800-$2BFF // ・右下:$2C00-$2FFF /* (0,0) (256,0) (511,0) +-----------+-----------+ | | | | | |...
Rust
0
无聊,\n', '不过还是听从专业人士的意见吧。', TxtCtl.Enter, ), ) CloseMessageWindow() ChrTalk( 0x00FE, ( '请一定把其它的学生\n', '也救出来啊。', TxtCtl.Enter, ), ) CloseMessageWindow() Jump('loc_1E8B') def _loc_1CE0(): pass ...
Python
1
6 | recv_mpst_b_from_h, RoleH, 7 | recv_mpst_b_from_i, RoleI, 8 | recv_mpst_b_from_j, RoleJ, 9 | recv_mpst_b_from_k, RoleK, 10 | => RoleB, MeshedChannelsEleven, 11 ); // C create_recv_mpst_session_bundle!( recv_mpst_c_from_a, RoleA, 1 | recv_mpst_c_from_b, RoleB, 2 | recv_mpst_c_from_d,...
Rust
0
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or module...
Python
1
TA: mod_str.append("Meta") mod_debug = "+".join(mod_str) if mod_str else "None" print(f"🎯 KEY: Key={keycode}, Raw={raw_keycode}, Mod={modifiers}({mod_debug})") # ✅ SEMPRE CONSENTI il TAB (navigazi...
Python
1
tus messages label = tk.Label(root, text="No file selected", bg="black", fg="white") label.pack() # Create a label to display the image detecting_img = tk.Label(root, bg="black") detecting_img.pack() normal_img = tk.Label(root, bg="black") normal_img.pack() labelcount = tk.Label(root, text="", bg="black", fg="white"...
Python
1
:forget(self); ptr.as_ptr() } pub unsafe fn from_raw(ptr: *mut sys::rs2_device_hub) -> Self { Self { ptr: NonNull::new(ptr).unwrap(), } } } impl Drop for DeviceHub { fn drop(&mut self) { unsafe { sys::rs2_delete_device_hub(self.ptr.as_ptr()); ...
Rust
0
Services'*"] pub const PXE_CALLBACK_RECV_REQUEST: u32 = 0u32; #[doc = "*Required features: 'Win32_System_DeploymentServices'*"] pub const PXE_CALLBACK_SERVICE_CONTROL: u32 = 2u32; #[doc = "*Required features: 'Win32_System_DeploymentServices'*"] pub const PXE_CALLBACK_SHUTDOWN: u32 = 1u32; #[doc = "*Required features: ...
Rust
0
"""Tests for the Freebox utility methods.""" import json from homeassistant.components.freebox.router import is_json from .const import DATA_LAN_GET_HOSTS_LIST_MODE_BRIDGE, DATA_WIFI_GET_GLOBAL_CONFIG async def test_is_json() -> None: """Test is_json method.""" # Valid JSON values assert is_json("{}") ...
Python
1
0, -1.0, 0.0), ]) } } pub struct Back; impl Side for Back { const SIDE: usize = 5; const DX: isize = 0; const DY: isize = 0; const DZ: isize = 1; fn offset<T: Voxel>() -> isize { T::DZ as isize } fn accept<T: Voxel>(_: usize, _: usize, z: usize) -> bool { z < ...
Rust
0
; Self::buffer_size()] } // HEIGHT const fn height_offset() -> usize { 0 } const fn height_size() -> usize { size_of::<Bytes4>() } const fn height_range() -> Range<usize> { Self::height_offset()..(Self::height_offset() + Self::height_size()) } // PREFIX ...
Rust
0
else: iusage_percent = 0 if usage_percent >= 0.8: disk_detail.append({ "name": key, "percent": usage_percent*100, "ipercent": iusage_percent*100, "usage": usag...
Python
1
>prev, head); } */ /* pub void INIT_LIST_HEAD(struct list_head_t *list) { list->next = list; list->prev = list; } */ /* pub void link_list_item(dmac_channel_number_t channel_num, uint8_t LLI_row_num, int8_t LLI_last_row, ...
Rust
0
nsstring = NSString(Id::from_ptr(webkit_version)); let () = msg_send![bundle, unload]; Ok(nsstring.to_str().to_string()) } } impl Drop for InnerWebView { fn drop(&mut self) { // We need to drop handler closures here unsafe { if !self.ipc_handler_ptr.is_null() { let _ = Box::from_raw(self.ipc_handler_p...
Rust
0
if ray_length < ray_length_in_voxel { d.x = self.dist_voxel((*p + Vec3::splat(0.5)).gl_fract() - Vec3::splat(0.5)); if d.x < DELTA { break; } } else if ray_length < ray_length_check_voxel { let mut ray_delta: Vec...
Rust
0
k | wn_attack_mask | wb_attack_mask | wr_attack_mask)).count_ones() as i32; }, def::BQ => { b_feature_map.mg_sqr_point += SQR_TABLE_BQ[index]; let threat_val = val_of(piece); if index_mask & b_attack_mask == 0 { if index_mask &...
Rust
0
f2282 = step(*(float2*)buf2283, *(float*)buf2284); *(float3*)buf2285 = step(*(float3*)buf2286, *(float*)buf2287); *(float4*)buf2288 = step(*(float4*)buf2289, *(float*)buf2290); *(float*)buf2291 = tan(*(float*)buf2292); *(float2*)buf2293 = tan(*(float2*)buf2294); *(float3*)buf2295 = tan(*(float3*)buf...
Rust
0
); tree_builder.token(IDENT, "a"); tree_builder.finish_node(); tree_builder.finish_node(); // declarator tree_builder.finish_node(); // list tree_builder.finish_node(); // declaration let root = tree_builder.finish(); let var_decl = JsVariableDeclaration::cast(...
Rust
0
open("/proc/modules")?), buffer: String::with_capacity(512), }) } } impl Iterator for ModuleIter { type Item = io::Result<Module>; fn next(&mut self) -> Option<Self::Item> { self.buffer.clear(); match self.file.read_line(&mut self.buffer) { Ok(read) if read ...
Rust
0
#[test] fn sim_blind_4x2() { sim(&build_model(BlindCfg { num_cohorts: 4, txns_per_cohort: 2, extents: &[8], name: name_of(&sim_blind_4x2) }), 160); } <filename>src/constants.rs pub const LINE_REQUEST_ID_HTTP_HEADER_NAME: &'static str = "x-line-request-id"; use std::path::Path; ...
Rust
0
# raw_to_bronze import os import snowflake.connector from botocore.exceptions import ClientError, BotoCoreError def lambda_handler(event, context): try: # Snowflake credentials from Lambda environment variables conn = snowflake.connector.connect( user=os.environ['user'], passw...
Python
1
) .field("mod_name_shift", &self.mod_name_shift) .field("mod_name_control", &self.mod_name_control) .field("mod_name_alt", &self.mod_name_alt) .field("mod_separator", &self.mod_separator) .field("_gtk_reserved1", &self._gtk_reserved1) .field("_gtk_reserved2", &self....
Rust
0
: log::Level, #[structopt(flatten)] output: git_cvs_fast_import_process::Opt, #[structopt( short, long, parse(from_os_str), help = "the file storing the repository metadata. If this file doesn't exist, it will be created, and the import will be treated as being from scratch...
Rust
0
_x = value, LY_REGISTER => {} // Read-only LYC_REGISTER => self.lcd_status.lyc = value, BG_PALETTE => self.bg_palette = value, OBJ_PALETTE_0 => self.obj0_palette = value, OBJ_PALETTE_1 => self.obj1_palette = value, WINDOW_Y_REGISTER => self.window_...
Rust
0
from moviepy import VideoFileClip, TextClip, CompositeVideoClip from faster_whisper import WhisperModel def transcribe_audio(video_path, model_size="small", device="cpu", compute_type="int8", language="es"): """ Transcribe el audio de un video usando Whisper y devuelve una lista de palabras con sus tiempos. ...
Python
1
DEBUG, INFO, WARN, ERROR, FATAL, } impl FromStr for LogSeverity { type Err = Error; fn from_str(s: &str) -> Result<Self, Error> { match s.to_lowercase().as_str() { "fatal" => Ok(LogSeverity::FATAL), "error" => Ok(LogSeverity::ERROR), "warn" | "warn...
Rust
0
""" pygments.lexers.supercollider ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Lexer for SuperCollider :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, include, words, default from pygments.token impo...
Python
1
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """The data layer used during training to train a Fast R-CNN network. ...
Python
1
"""Main module for terminal-flag-banner package.""" import argparse from .flag_banner import ( TextBanner, generate_flag, display_flag_list_to_terminal, generate_random_country_code, ) def main(): parser = argparse.ArgumentParser( description="Display a flag banner in the terminal." )...
Python
1
logging.TRACE: "%s", logging.DEBUG: "%s", logging.INFO: "%s", logging.WARNING: ANSI.COLOR_WARNING + "%s" + ANSI.COLOR_DEFAULT, logging.ERROR: ANSI.COLOR_ERROR + "%s" + ANSI.COLOR_DEFAULT, logging.CRITICAL: ANSI.COLOR_CRITICAL + "%s" + ANSI.COLOR_DEFAULT, } def f...
Python
1
kwargs['inflictedStatus']) # battleContext.eventQueue.trigger(battleContext=battleContext, eventContext=eventContext, trigger=Trigger.AFTER_STATUS) # class StatusSelf(ExecutionBehavior): # """Implements execution behavior for statusing self # This class implements a statusing self behavior. #...
Python
1
#!/usr/bin/python3 """ Printing a square Function name:-> print_square. """ def print_square(size): """ Prints a square. Args: size: The size of the square to be printed. Returns: Nothing. """ if not isinstance(size, int): raise TypeError("size must be an integer") ...
Python
1
nwrap_or(&pcap::HARDWARE_ADDR_UNSPECIFIED), src_ip_addr, ); // Ethernet let ethernet = Ethernet::new(arp.kind(), arp.src_hardware_addr(), arp.dst_hardware_addr()).unwrap(); // Indicator let indicator = Indicator::new(Layers::Ethernet(ethernet), Some(Laye...
Rust
0
krate as _oauth1_request; #[allow(nonstandard_style)] fn #dummy #fn_generics(mut #dummy: (&#name #ty_generics, #dummy)) -> #dummy::Output #where_clause { #body } impl #impl_generics _oauth1_request::Request for #name #ty_generics ...
Rust
0
from encodec import EncodecModel import torch import torch.nn as nn class EncodecQuantizer(nn.Module): def __init__(self, n=8, frozen=True, scale=1.0): super().__init__() model = EncodecModel.encodec_model_24khz() self.model = model.quantizer self.scale = scale #Modify state...
Python
1
ing...") break case _: pass def uninstall(): manager = ToastNotificationManager.get_default() notifier = manager.create_toast_notifier_with_id(APP_USER_MODULE_ID) # Remove any scheduled notifications that haven't been shown yet. Do # this first to avoid rac...
Python
1
import numpy as np import torch import vae from pyga import Individual, blended, gaussian class ShapeVAE(Individual): _crossover_method = staticmethod(blended) _mutate_method = staticmethod(gaussian) target_shape = None model = None def __init__(self, genes, model=None): super().__in...
Python
1
will be a hash of both the previous ID and /// the signature. If num_hashes is zero and there's no transaction data, /// start_hash is returned. pub fn next_hash( start_hash: &Hash, num_hashes: u64, transactions: &[VersionedTransaction], ) -> Hash { if num_hashes == 0 && transactions.is_empty() { ...
Rust
0
# coding=utf-8 """ 通过paddlenlp获取相关的信息 # 首次更新完以后,重启后方能生效 !pip install --upgrade paddlenlp==2.3.0 !pip install pypinyin !pip install LAC !pip install paddlepaddle==2.3.0 """ from pprint import pprint from paddlenlp import Taskflow if __name__ == '__main__': # extract_paddlenlp_info(None) import paddle import...
Python
1
if score >= self.offsets.len() || diag < self.diags[score].0 || diag > self.diags[score].1 { // offsets is always ahead by 1, since we know the len of a layer // when it's created. Adding a new layer updates the offset of the next layer. None } else { let...
Rust
0
import torch def preprocess_panoptic_gt(gt_labels, gt_masks, gt_semantic_seg, num_things, num_stuff, img_metas): """Preprocess the ground truth for a image. Args: gt_labels (Tensor): Ground truth labels of each bbox, with shape (num_gts, ). gt_masks (Bit...
Python
1
r (batch, num_classes) target (Tensor): A tensor of ground truth labels of shape (batch, num_classes) or (batch) """ if target.ndim == 1 and self.num_classes > 1: target = F.one_hot(target, self.num_classes) if probs.ndim <= 2: ...
Python
1
# ========= Copyright 2023-2024 @ CAMEL-AI.org. 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/licenses/LICENSE-2.0 # # Unless requ...
Python
1
assert_eq!(lower(&[ SubRR(EAX, EBX) ]), vec![ 0x29, 0b11000011 ]); assert_eq!(lower(&[ SubRR(R8D, EBX) ]), vec![ 0b1000100, 0x29, 0b11000011 ]); assert_eq!(lower(&[ SubRR( AX, BX) ]), vec![ 0x66, 0x29, 0b11000011 ]); assert_eq!(lower(&[ SubRR(R8W, BX) ]), vec![ 0x66, 0b1000100, 0x29...
Rust
0
from typing import Any from sqlalchemy import MetaData from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm.exc import DetachedInstanceError class AlchemyBaseModel(DeclarativeBase): __abstract__ = True metadata = MetaData( naming_convention={ "ix": "ix_%(column_0_label)s", ...
Python
1
false => args.extend(&["-O0", "-g"]), } args }; } pub fn sgx_sdk() -> PathBuf { Path::new(&SGX_SDK.to_string()).to_path_buf() } pub fn sgx_sdk_untrusted_includes() -> Vec<PathBuf> { vec![sgx_sdk().join("include")] } pub fn sgx_sdk_includes() -> Vec<PathBuf> { vec![ sgx_sdk().j...
Rust
0
b'r', b'u', b'm', b'q', // payload. username = 'rumq' 0x00, 0x02, b'm', b'q', // payload. password = 'mq' 0xDE, 0xAD, 0xBE, 0xEF, // extra packets in the stream ]; stream.extend_from_slice(&packetstream[..]); let packet = mqtt_read(&mut stream, 100).unwrap(); le...
Rust
0