text
string
label_name
string
labels
int64
import librosa import numpy as np import pretty_midi import mir_eval.melody def get_highest_pitches_from_piano_roll(pr): """ params: pr : (128, time(frame)) return: highest_pitches : (time(frame), ) """ highest_pitches = [] for i in range(pr.shape[1]): ps = np.nonzero(...
Python
1
linking directly between entries within the same DNA or in * remote DNAs, as identities are treated as tuples of `(DnaHash, EntryHash)`. * * @see ../README.md * @package HDK Graph Helpers * @since 2019-05-16 */ use hdk::prelude::*; use crate::{ RevisionHash, DnaAddressable, RecordAPIResult, re...
Rust
0
interval: Option<u16>, pub is_admin: bool, pub is_disabled: bool, pub is_redeemed: bool, } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] pub struct Peer { pub id: i64, #[serde(flatten)] pub contents: PeerContents, } impl Deref for Peer { type Target = PeerContents; fn de...
Rust
0
/// This has the nice benefit of getting our automatic rewind /// capability from the point and the grammar logic can stay clean. pub(crate) struct TokenPoint<'s, T: 's> { pub offset: usize, pub sub_offset: Option<u8>, pub s: &'s [T], } impl<'s, T: 's> fmt::Debug for TokenPoint<'s, T> { fn fmt(&self, f...
Rust
0
await?; let f = async move { let sleep = rand::thread_rng().gen_range(0, 25); time::sleep(Duration::from_millis(sleep)).await; let (len, uri) = gen_uri(&authority); let req = Request::get(&uri[..]) .header("Content-Length", len) ....
Rust
0
""" @author: Khera """ import time from binance.client import Client import csv import pandas as pd import numpy as np def emaPoints(data, dataPoints): ema1 = [] for i in range(len(data)): ema = 0 if i > 0: prevEma = ema1[i-1] multiplyer = 2/(dataPoints+1) ...
Python
1
match &self { ZcashPrivateKey::<N>::P2PKH(p2pkh) => write!(f, "{}", p2pkh.to_string()), ZcashPrivateKey::<N>::Sprout(sprout) => write!(f, "{}", sprout.to_string()), ZcashPrivateKey::<N>::Sapling(sapling) => write!(f, "{}", sapling.to_string()), _ => write!(f, ""), ...
Rust
0
_cmp!(Rev<T>; |a, b| b.0.partial_cmp(&a.0).unwrap(); where T: PartialOrd); mod ids; mod node; mod state; #[cfg(test)] mod unit_tests; use crate::{error::client::Result, ports::Client}; use async_std::task; use futures::executor::block_on; use ids::Ids; use node::{Node, NodeId}; use state::State; #[derive(Debug)] pub ...
Rust
0
# -*- coding: utf-8 -*- from django.contrib import admin from article.models import * @admin.register(OwnerMessage) class OwnerMessageAdmin(admin.ModelAdmin): list_display = ('id', 'summary', 'created_at') list_per_page = 10 class Media: css = { 'all': ('/static/css/manager.css',) ...
Python
1
pler", &glIsSampler_p, sampler); #[cfg(all(debug_assertions, feature = "debug_automatic_glGetError"))] { global_automatic_glGetError("glIsSampler"); } out } static glIsSampler_p: APcv = ap_null(); /// Tries to load [`glIsSampler`], returns if a non-null pointer was obtained. #[doc(hidden)]...
Rust
0
import networktables as networkTablesCore import keyboard import time from threading import Timer def main(): def release_key(key_name: str) -> None: print(f"Sending: {key_name} -> {False}") table.putBoolean(key_name, False) def timed_keypress(key_name: str, press_time: float) -> None: ...
Python
1
# Load modules from __future__ import print_function import os import pandas as pd import numpy as np from matplotlib import pyplot as plt # Change working Directory os.chdir('C:/Users/pp9596/Documents/02 ZSP/00 PACKT/Book - Practical Time-Series Analysis/Avishek') #Read dataset into a pandas.DataFrame beer_df = pd.r...
Python
1
from selenium.webdriver.common.by import By # from utilities.selenium_utils import Utils from selenium.webdriver.remote.webdriver import WebDriver from base.base_driver import BaseDriver from selenium.webdriver.remote.webelement import WebElement class TmHomePage(BaseDriver): def __init__(self, driver: WebDriver)...
Python
1
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c), 2013-2025, John McNamara, jmcnamara@cpan.org # from xlsxwriter.workbook import Workbook from ..excel_comparison_test import ExcelComparisonTest class...
Python
1
; Ok(address.required_signers()) } /// Returns public key of current signer pub fn public_key(&self, name: &str, root_hash: &H256, enckey: &SecKey) -> Result<PublicKey> { let address = self.get_multi_sig_address_from_root_hash(name, root_hash, enckey)?; Ok(address.self_public_key(...
Rust
0
imal value #[inline] pub fn get_color(hex_value: i32) -> Color { unsafe { ffi::GetColor(hex_value).into() } } /// Color fade-in or fade-out, alpha goes from 0.0f to 1.0f #[inline] pub fn fade(&self, alpha: f32) -> Color { unsafe { ffi::Fade(self.into(), alpha).into() } } ...
Rust
0
import re from collections import defaultdict class Uniswap: def __init__(self): self.token_balances = defaultdict(lambda : 0) def process(self, tx): tx = tx.replace(';', '') if 'adds' in tx: self.add_liquidity(tx) elif 'removes' in tx: self.r...
Python
1
self["title"] = _v _v = arg.pop("uid", None) _v = uid if uid is not None else _v if _v is not None: self["uid"] = _v _v = arg.pop("uirevision", None) _v = uirevision if uirevision is not None else _v if _v is not None: self["uirevision"] = _v ...
Python
1
#[pallet::weight((<T as Config>::WeightInfo::get_price(), DispatchClass::Operational))] pub fn get_price(origin: OriginFor<T>,currency_id1: CurrencyId, currency_id2: CurrencyId) -> DispatchResultWithPostInfo { let price = <Self as PriceData<CurrencyId>>::get_price(currency_id1,currency_id2).ok_or(Error::<T>::Overf...
Rust
0
) * (total_original_frames - total_processed_frames) if total_processed_frames > 0 and total_processed_frames < total_original_frames else 0 status_text.info(f"Procesando frame {total_processed_frames}/{total_original_frames}... ETA: {eta:.0f}s") # --- Limpieza Final --- cap.release(); tfil...
Python
1
:IntTy::I64) | (ty::IntTy::I128, chalk_ir::IntTy::I128) ), (ty::Uint(ty1), Scalar(Uint(ty2))) => matches!( (ty1, ty2), (ty::UintTy::Usize, chalk_ir::UintTy::Usize) | (ty::UintTy::U8, chalk_ir::UintTy:...
Rust
0
start_height: u32) -> DBIterator { // [height u32] -> [blockhash U256] let key = big_endian_from_u32(start_height); // include_start = true self.block_index .iterator(IteratorMode::From(&key, Direction::Forward)) } pub fn read_tx(&self, hash: &U256) -> Result<Option...
Rust
0
p.file_name() .unwrap_or(OsStr::new("")) .to_str() .unwrap_or("") ) } use cargo_snippet::snippet; #[snippet("Modulo")] #[snippet("ncr")] pub struct Modulo { fact: Vec<usize>, inv_fact: Vec<usize>, modulo: usize } #[snippet("Modulo")] #[snippet("ncr")] impl Modulo { pub fn new(n: ...
Rust
0
#if self.prefix=='face': # #print('fg-bg', self.stride, n_fg, num_bg) # STAT[0]+=1 # STAT[self.stride][0] += config.TRAIN.RPN_BATCH_SIZE # STAT[self.stride][1] += n_fg # STAT[self.stride][2] += np.sum(fg_score[fg_inds]>=0) # #_sta...
Python
1
from ipaddress import ip_network from ..schema import schema from .base import OpenWrtConverter class Rules(OpenWrtConverter): netjson_key = "ip_rules" intermediate_key = "network" _uci_types = ["rule", "rule6"] _schema = schema["properties"]["ip_rules"]["items"] def to_intermediate_loop(self, b...
Python
1
none().0) } } #[cfg(any(feature = "v2_8", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_8")))] fn user_data(&self) -> Option<glib::Variant> { unsafe { from_glib_none(ffi::webkit_context_menu_get_user_data(self.as_ref().to_glib_none().0)) } ...
Rust
0
# Copyright 2023 The Google Earth Engine Community Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
Python
1
rgb, gt_images).mean().double() psnr_test = psnr(rgb.squeeze(), gt_images.squeeze()).mean().double() ssims_test = ssim(rgb, gt_images, size_average=True).mean().item() lpips_vgg_test = self.lpips_func(rgb, gt_images).mean().item() metric_dict = {"L1_loss": L1_loss, ...
Python
1
; use std::env; extern crate muses_driver; use std::io::stdin; pub fn main() { let args: Vec<String> = env::args().collect(); let mut opts = Options::new(); opts.optflag("", "sensel-only", "Only run sensel driver not full muses instrument"); opts.optflag("h", "help", "print this help menu"); le...
Rust
0
bj = _parse_date(date_str).date() days_ahead = (date_obj - today).days return [ days_ahead, date_obj.weekday(), # Segunda=0, Domingo=6 date_obj.month, 1 if _is_holiday(date_str) else 0 ] # Features para...
Python
1
} } /// Change max size of payload. By default max size is 256Kb pub fn limit(mut self, limit: usize) -> Self { self.limit = limit; self } } impl<U> Future for XmlBody<U> where U: DeserializeOwned + 'static, { type Output = Result<U, XMLPayloadError>; fn poll(mut ...
Rust
0
, // Accept 0x00, // MBZ 0xbb, 0x80, // Port 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // SID, 16 octet 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // MBZ, 12 octets 0x00, 0x00, 0x00...
Rust
0
_rules! bad_request_display { ($t: ty) => { impl Reply for $t { #[inline] fn into_response(self) -> Response { hyper::Response::builder() .status(StatusCode::BAD_REQUEST) .body(format!("{}", self).into()) .un...
Rust
0
store.as_context_mut().0; // Should be safe since `T` is connecting the linker and store Some(unsafe { self._get(module, name)?.to_extern(store) }) } fn _get(&self, module: &str, name: &str) -> Option<&Definition> { let key = ImportKey { module: *self.string2idx.get(module)...
Rust
0
[u16; 16], /// A pointer, pointing to the current position in the stack. stack_pointer: u8, /// A helper variable to properly implement the timer resolution. cycles_since_timer_dec: u8, /// A flag that indicates whether the output pins changed since it /// was last set to false. draw: bo...
Rust
0
writeln!(out, "#version {}\n", options.version)?; if es { writeln!(out, "precision highp float;\n")?; } let mut counter = 0; let mut names = FastHashMap::default(); let mut namer = |name: Option<&'a String>| { if let Some(name) = name { if !is_valid_ident(name) || ...
Rust
0
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/gui/Scaleform/genConsts/STORE_CONSTANTS.py class STORE_CONSTANTS(object): SHOP = 'shop' INVENTORY = 'inventory' STORE_ACTIONS = 'storeActions' STORE = 'store' ACTION_EMPTY_LINKAGE = 'StoreActionsEmptyUI' AC...
Python
1
Parser<T: Clone> { fn parse_endpoint(&self, input: String) -> T; } impl<T: Clone> EndpointSelector<T> { pub fn new<P: EndpointParser<T>>(endpoints: Vec<String>, parser: P, strategy: Box<dyn EndpointStrategy<T> + Send + Sync>) -> Self { EndpointSelector { endpoints: endpoints ...
Rust
0
import ctypes import uuid """ le == little endian """ def _read8(mm, le=True): x = mm.read(8) if le: n = x[0] | x[1] << 8 | x[2] << 16 | x[3] << 24 | x[4] << 32 | x[5] << 40 | x[6] << 48 | x[7] << 56 else: n = x[7] | x[6] << 8 | x[5] << 16 | x[4] << 24 | x[3] << 32 | x[2] << 40 | x[1] << ...
Python
1
s not elegant since it bloats the binary, but the fonts are //! actually quite small (couple hundred K) and Rust-binaries are //! already huge (> 50M at time of writing), so I'd say its a good //! tradeoff for not having to deal with fonts missing and most //! importantly, trying to figure out where the fuck the fonts ...
Rust
0
#!/usr/bin/env python3 # coding=utf-8 import requests as r from .yblogin import BASEURL class feed: def __init__(self, token): self.token = token ''' 发起动态 ''' def add(self, content, privacy_level): payload = { 'content': content, 'privacy': privacy_leve...
Python
1
col_offsets = col_block_start + tl.arange(0, BLOCK_SIZE_COLS) col_mask = col_offsets < num_cols grad_to_add = tl.load( grad_output_row_ptr + col_offsets, mask=col_mask, other=0.0 ) tl.atomic_add( grad_input_row_ptr + col_off...
Python
1
the supplied record would cause the file to exceed the size limit we have. is%s iiN(RRR&Rtformattseekttelltlen(R Rtmsg((s handlers.pyRs"N(RRRRRRR(((s hand...
Python
1
""" Write a python function to find the index of smallest triangular number with n digits. https://www.geeksforgeeks.org/index-of-smallest-triangular-number-with-n-digits/ assert find_Index(2) == 4 """ from math import ceil, sqrt def find_Index(n): """ :param n: int :return: int """ triangular_numb...
Python
1
torch.max(masked_heatmap, masked_gaussian * k, out=masked_heatmap) return heatmap class SELayer_Linear(nn.Module): def __init__(self, channels, act_layer=nn.ReLU, gate_layer=nn.Sigmoid): super().__init__() self.conv_reduce = nn.Linear(channels, channels) self.act1 = act_layer() ...
Python
1
try_uniform_components: usize, pub combined_texture_image_units: usize, pub combined_uniform_blocks: usize, pub combined_vertex_uniform_components: usize, pub cube_map_texture_size: usize, pub depth_texture_samples: usize, pub draw_buffers: usize, pub dual_source_draw_buffers: usize, pub...
Rust
0
P85 = _common_types.SP85 SP86 = _common_types.SP86 SP87 = _common_types.SP87 SP88 = _common_types.SP88 SP89 = _common_types.SP89 SP90 = _common_types.SP90 SP91 = _common_types.SP91 SP92 = _common_types.SP92 SP93 = _common_types.SP93 SP94 = _common_...
Python
1
import pytest from shot_scraper.utils import filename_for_url @pytest.mark.parametrize( "url,ext,expected", ( ("https://datasette.io/", None, "datasette-io.png"), ("https://datasette.io/tutorials", "png", "datasette-io-tutorials.png"), ( "https://datasette.io/-/versions.jso...
Python
1
ack"] = feedback # yield joined_df aggregated_df = pd.concat([aggregated_df, joined_df]) aggregated_df = left_shift_pmid(aggregated_df) return aggregated_df def convert_to_eval_format(joined_df): """ Convert the joined dataframe to the evaluation format """ join...
Python
1
} except Exception as e: logging.error(f"[CRAWLER ERROR] Failed to initiate call: {e}") raise HTTPException(status_code=500, detail="Twilio call failed to start.") @app.post("/twilio/voice") async def handle_twilio_voice(request: Request): vr = VoiceResponse() gather = Gather(...
Python
1
} } impl Display for RotationType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { RotationType::Normal => write!(f, ""), RotationType::Double => write!(f, "2"), RotationType::Inverse => write!(f, "'"), } } } /// Gives ...
Rust
0
rror)? .as_str() .ok_or(Error::JwsParseError)?; let jws_protected_string_decoded = base64_url::decode(&jws_protected_encoded)?; let jws_jwm_header: JwmHeader = serde_json::from_slice(&jws_protected_string_decoded)?; let payload_string_encoded = jws_object .get("payload") .ok...
Rust
0
enum Node { EncodedBytes(EncodedBytes), ClearBytes(ClearBytes), } pub type Ast = Vec<Node>; #[derive(Debug)] pub enum Error { DecodeUtf8Error(str::Utf8Error), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::DecodeUtf8Erro...
Rust
0
'Try to increase PerlTidy log level via user setting ' + '"perltidy_log_level" and try again.') finally: # Cleanup. if use_temporary_files and not get_perltidy_env_flag('keep_temp_files'): os.unlink(perltidy_input_filepath) os.unlink(perltidy_output_f...
Python
1
(&zero); } // println!("queue: {:?}", queue); if queue.is_empty() { break; } queue.sort_by(|a, b| { self.nodes[*a].cmp(&self.nodes[*b]) }); let node = queue.remove(0); match self.neighbors.get(&node) { Some(neighbors...
Rust
0
ned in RFC 5155. /// /// Only a proposed standard. const DSA_NSEC3_SHA1: u8 = 6; /// `RSASHA1-NSEC3-SHA1`. /// /// Defined in RFC 5155. /// /// Only a proposed standard. /// /// RFC 6944 states this is 'Recommended to Implement'. const RSASHA1_NSEC3_SHA1: u8 = 7; /// `RSA/SHA-256`. /// /// Defined in RF...
Rust
0
unused_mut)] let mut scope_739 = writer.prefix("Phase2EncryptionAlgorithm"); if let Some(var_740) = &input.phase2_encryption_algorithms { let mut list_742 = scope_739.start_list(true, Some("item")); for item_741 in var_740 { #[allow(unused_mut)] let mut entry_743 = list_7...
Rust
0
age) .finish() } } #[repr(C)] pub struct GtkRecentInfo(c_void); impl ::std::fmt::Debug for GtkRecentInfo { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GtkRecentInfo @ {:?}", self as *const _)) .finish() } } #[repr(C)] #[derive(Co...
Rust
0
import os import pandas as pd import matplotlib.pyplot as plt test_dir = "/workspace/my_auxiliary_persistent/natmed_multitrial_results_synthetic_data/" fig_out_dir = "/workspace/my_auxiliary_persistent/natmed_multitrial_results_plots_synth_ground" def extract_auc_and_ci(test_dir): folder_names = [] auc_mea...
Python
1
into!(i32, usize); vec_into!(i32, f32); vec_into!(i32, f64); vec_into!(i64, isize); vec_into!(i64, u8); vec_into!(i64, u16); vec_into!(i64, u32); vec_into!(i64, u64); vec_into!(i64, usize); vec_into!(i64, f32); vec_into!(i64, f64); vec_into!(isize, u8); vec_into!(isize, u16); vec_into!(isize, u32); vec_into!(isize, u...
Rust
0
DELETE b" ) check_state() for node in list(cluster.instances.values()): node.restart_clickhouse() check_state() # drop executed on the third node node = cluster.instances[NODE03] node.query(f"{STMT_DROP} foobar ON CLUSTER 'cluster'") node.query( f"{STMT_DROP} IF EXISTS...
Python
1
register::<GunslingerComponent>(); ecs.register::<RewardsComponent>(); ecs.register::<PlayerAlly>(); // If you add additional components remember to update saveload.rs // This we do not serialized this as it contains function pointers ecs.register::<super::EventComponent>(); ecs.insert(super::E...
Rust
0
# file: vulnerability-assessment-service/app/api/endpoints.py from fastapi import APIRouter, status from celery.result import AsyncResult from app.models.models import ScanRequest, TaskStatus from app.task import run_openvas_scan router = APIRouter() @router.post("/scans", status_code=status.HTTP_202_ACCEPTED) async ...
Python
1
from opencompass.openicl.icl_prompt_template import PromptTemplate from opencompass.openicl.icl_retriever import ZeroRetriever from opencompass.openicl.icl_inferencer import GenInferencer from opencompass.openicl.icl_evaluator import AccEvaluator from opencompass.datasets import CommonsenseQADataset_CN from opencompass...
Python
1
) try: shape = cmdx.encode(path) except cmdx.ExistError: # Backwards compatibility, before meshes were exported if not self._registry.has(entity, "ConvexMeshComponents"): if shape_type == constants.MeshShape: ...
Python
1
fsb224_100 100; fsb224_1000 1000; fsb224_10000 10000; ); bench_update!( Fsb256::default(); fsb256_10 10; fsb256_100 100; fsb256_1000 1000; fsb256_10000 10000; ); bench_update!( Fsb384::default(); fsb384_10 10; fsb384_100 100; fsb384_1000 1000; fsb384_10000 10000; )...
Rust
0
s_ref()], None, None, )?; } repo }; Ok(BuildData(repo)) } } /// Contains all the mappings for a specific version pub struct SpigotMappings { pub class_mappings: FrozenMappings, pub member_mappings: FrozenMappings...
Rust
0
#[serde(rename = "additionalData", default, skip_serializing_if = "Option::is_none")] pub additional_data: Option<serde_json::Value>, #[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")] pub friendly_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deseria...
Rust
0
from pydantic import Field, PositiveInt from pydantic_settings import BaseSettings class MyScaleConfig(BaseSettings): """ Configuration settings for MyScale vector database """ MYSCALE_HOST: str = Field( description="Hostname or IP address of the MyScale server (e.g., 'localhost' or 'myscale....
Python
1
have_read += n; if have_read == buf.len() { *current_part_number = new_part_number; return Some(PartData { data: buf, part_numbe...
Rust
0
Adds or sets a new tile for a given layer. /// Returns an error if the tile is out of bounds. /// It's important to know that the new tile wont exist until bevy flushes /// the commands during a hard sync point(between stages). /// A better option for updating existing tiles would be the following: ...
Rust
0
import mynn as nn import cupy as np from struct import unpack from draw_tools.plot import plot import gzip import matplotlib.pyplot as plt import pickle np.random.seed(309) batch_size = 32 num_epochs = 10 log_iters = 100 save_dir = 'best_model' train_images_path = r'.\dataset\MNIST\train-images-idx3-ubyte.gz' train_...
Python
1
from juliacall import Main as jl # Import the Julia package manager jl.seval("using CrystalNets") print("Success CrystalNets") data = """ 12,4.6997,7.1199,3.6592,1.5708,2.1366,1.5708,0,0.438,0.8075,0.6503,2,0.0,0.9344,0.5,-1,-1.0,-1.0,-1.0,-1,-1.0,-1.0,-1.0,-1,-1.0,-1.0,-1.0,-1,-1.0,-1.0,-1.0,-1,-1.0,-1.0,-1.0,-1,-1.0...
Python
1
#!/usr/bin/env python # # Copyright 2016 Cisco Systems, Inc. # # 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 applicab...
Python
1
from Packets.Messages.Server.TeamLeftMessage import TeamLeftMessage from Utils.Reader import ByteStream from Logic.Player import Player from Database.DatabaseManager import DataBase from Packets.Messages.Server.TeamChatServerMessage import TeamStreamMessage from Packets.Messages.Server.TeamMessage import TeamMessage c...
Python
1
icode(info['nielsen']['title']).encode('utf8').replace('"','').replace("'","")) ret['descs'].append(u'Cat.: %s. Subcat.: %s. %s'.encode('utf8') % (info['nielsen']['category'].encode('utf8'),info['nielsen']['subcategory'].encode('utf8'),info['nielsen']['title'].encode('utf8'))) return ret ...
Python
1
Renderable { fn render<C, G>(&self, c: Context, gfx: &mut G, size: (u32, u32), scale: u32, glyphs: &mut C) where C: CharacterCache, G: Graphics<Texture=C::Texture>; } impl Renderable for Game { fn render<C, G>(&self, c: Context, gfx: &mut G, size: (u32, u32), scale: u32, glyphs: &mut C) where C...
Rust
0
ue self.waiting_for_input = False self.script = [] self.script_index = 0 def start(self, entity, text, bottom_mode=True, show_left=True): self.entity = entity self.text = text self.bottom_mode = bottom_mode self.show_left = show_left self.active = Tr...
Python
1
pi = 3.14159 straal = float(input("Voer de straal van de cirkel in:\n")) oppervlakte = straal * straal * pi omtrek = 2 * pi * straal print(f"De oppervlakte van een cirkel met straal {straal} is {oppervlakte}") print(f"De omtrek van de cirkel met straal {straal} is {omtrek}")
Python
1
<h1>Big Text</h1> //! </body> //! </html>"#; //! //! fn main() -> Result<(), css_inline::InlineError> { //! let inliner = css_inline::CSSInliner::options() //! .load_remote_stylesheets(false) //! .build(); //! let inlined = inliner.inline(HTML); //! // Do something with inlined HTML, e.g. se...
Rust
0
1D( target, 0, format, w as GLsizei, 0, pix, typ, ::std::ptr::null() ); }, t::Kind::D1Array(w, a) => unsafe { gl.TexImage2D( target, ...
Rust
0
= checker_concat!( "four_players_game_sync", EndpointAFull, EndpointBFull, EndpointCFull, EndpointDFull => [ EndpointAWin, Branches0BfromA, Win, Branches0CfromA, Win, Branches0DfromA, Win ], [ ...
Rust
0
from typing import Union from colbert import Searcher from colbert.data import Queries from colbert.infra.config import ColBERTConfig TextQueries = Union[str, 'list[str]', 'dict[int, str]', Queries] class HopSearcher(Searcher): def __init__(self, *args, config=None, interaction='flipr', **kw_args): def...
Python
1
if conditional else 'unconditional'}_sample-{step}.txt", "w", ) as fp: for i in range(num_samples): if i != 0 and (i % math.sqrt(num_samples)) == 0: fp.write("\n") fp.write(f"{labels[i]} ") if prompts is not None: with ope...
Python
1
oll; use ergotree_ir::types::stype::SType; use ergotree_ir::types::stype_param::STypeVar; use crate::eval::tests::{eval_out_wo_ctx, try_eval_out_wo_ctx}; #[test] fn eval_index_of() { let coll_const: Constant = vec![1i64, 2i64].into(); let expr: Expr = MethodCall::new( c...
Rust
0
ing balance on conditional_offer. Returns None if max_discount not set on object. """ # max_discount will be None if not set in UI when created if conditional_offer.max_discount is not None: return conditional_offer.max_discount - conditional_offer.total_discount return None def generate_...
Python
1
neighbor_list = list(range(start_frame_idx, end_frame_idx, interval)) # random reverse if self.random_reverse and random.random() < 0.5: neighbor_list.reverse() # get the neighboring LQ and GT frames img_lqs = [] img_gts = [] for neighbor in neighbor_list: ...
Python
1
"""add cascading deletion to datasets from experiments Revision ID: 0584bdc529eb Revises: f5a4f2784254 Create Date: 2024-11-11 15:27:53.189685 """ import sqlalchemy as sa from alembic import op from mlflow.exceptions import MlflowException from mlflow.store.tracking.dbmodels.models import SqlDataset, SqlExperiment ...
Python
1
ttps://adventofcode.com/2020/day/20 /// Copyright 2021 by <NAME> /// Note: It isn't mentioned in the problem statement, but every edge /// in the provided tile-set has a unique complementary pairing. /// This makes the problem *MUCH* easier to solve. use std::collections::HashMap; #[path = "common.rs"] mod...
Rust
0
meout) } src.send_sync_packet(sync_uni, None).unwrap(); let received_result1: Vec<DMXData> = rx.recv().unwrap().unwrap(); let received_result2: Vec<DMXData> = rx.recv().unwrap().unwrap(); rcv_thread1.join().unwrap(); rcv_thread2.join().unwrap(); assert_eq!(received_result1.len(), 1); // ...
Rust
0
host"' sqlite_cursor.execute(sql) result = sqlite_cursor.fetchall() if len(result) != 0: # 若查询到有此表,才删除相应数据 sql = f"delete from tb_host where oid='{obj.oid}'" sqlite_cursor.execute(sql) # ★查询是否有名为'tb_host_include_credential_oid_list'的表★ 已废弃 # sql = 'SELECT...
Python
1
mod cache; mod cluster_admin; mod database; mod main_window; type CosmicVergeClient = basws_client::Client<api::Client>; use std::path::PathBuf; use clap::Clap; use tracing_subscriber::prelude::*; #[macro_use] extern crate tracing; #[cfg(debug_assertions)] const SERVER_URL: &str = "ws://localhost:7879/v1/ws"; #[cf...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' 在程序运行过程中,总会遇到各种各样的错误。 有的错误是程序编写有问题造成的,比如本来应该输出整数结果输出了字符串,这种错误通常称之为 bug,bug 是必须修复的。 有的错误是用户输入造成的,比如让用户输入 email 地址,结果得到一个空字符串,这种错误可以通过检查用户输入来做相应的处理。 还有一类错误是完全无法在程序运行过程中预测的,比如写入文件的时候,磁盘满了,写不进去了,或者从网络抓取数据,网络突然断掉了。 这类错误也称为异常,在程序中通常是必须处理的,否则,程序会因为各种问题终止并退出。 Python 内置了一套异常...
Python
1
# This file was generated by 'versioneer.py' (0.21) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json version_json = ''' { "date": "2025-03-13T12:48:15+0100", "dirty": false, "error...
Python
1
((input, label)) } } fn parse_statement<'def, 'r>( input: Tokens<'def, 'r>, id_gen: &mut IdGen, ) -> ParseResult<'def, 'r, Statement<'def>> { if let Ok((input, _)) = symbol(';')(input) { Ok((input, Statement::Empty)) } else if let Ok(ok) = assert::parse(input, id_gen) { Ok(ok) }...
Rust
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Python
1
ENT_METHOD_TO_ZAHLUNGSART[row["payment_method"]] == "Bar": barzahlungen += Decimal(row["total_price"]) ### businesscases.csv### # wir iterieren über die daten die wir in im einzelaufzeichnungsmodul aggregiert haben for gvtyp, summe in self.GV_SUMME.items(): for schlu...
Python
1
import tensorflow as tf import numpy as np import C3D_model import data_processing TRAIN_LOG_DIR = 'Log/train/' TRAIN_CHECK_POINT = 'check_point/train.ckpt-36' TEST_LIST_PATH = 'test.list' BATCH_SIZE = 10 NUM_CLASSES = 101 CROP_SZIE = 112 CHANNEL_NUM = 3 CLIP_LENGTH = 16 EPOCH_NUM = 50 test_num = data_processing.get_te...
Python
1
nsemble size doesn't double training time, as a test of parallel training. We allow some overhead, but should be significantly less than 2x """ # Create a larger dataset with more features to increase computation per network example_data = _get_example_data([10000, 10], [10000, 1]) # 10D input, 1D outp...
Python
1
from pathlib import Path import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from jupyter_scheduler.orm import Base from jupyter_scheduler.scheduler import Scheduler from jupyter_scheduler.tests.mocks import MockEnvironmentManager pytest_plugins = ("jupyter_server.pytest_plugin...
Python
1