text
string
label_name
string
labels
int64
from heapq import * def prim(start): # 시작 정점을 포함한 연결된 정점들 connected = {start} # 아직 연결되지 않은 간선들을 저장할 힙 unconnected = [(w, e) for e, w in graph[start]] heapify(unconnected) # 힙 속성 유지 sum_ = 0 # MST의 가중치 합 while unconnected: weight, vertex = heappop(unconnected) # 최소 가중치 간선 선택 ...
Python
1
T_SEPARATOR); check_subsequent_flags!(INTEGER_TRAILING_DIGIT_SEPARATOR, INTEGER_CONSECUTIVE_DIGIT_SEPARATOR); check_subsequent_flags!(INTEGER_CONSECUTIVE_DIGIT_SEPARATOR, FRACTION_INTERNAL_DIGIT_SEPARATOR); check_subsequent_flags!(FRACTION_INTERNAL_DIGIT_SEPARATOR, FRACTION_LEADING_DIGIT_SEPARATOR); check_subsequent_fl...
Rust
0
import os # 运行模式: LOCAL 为用户本地运行, CLOUD 为 PandAaI 官网运行 RUN_MODE = os.getenv("RUN_MODE", "LOCAL") SERVER_ROLE = os.getenv("SERVER_ROLE", "ALL") # API, CONSUMER, ALL # 日志配置 LOG_LEVEL = os.getenv("LOG_LEVEL", "DEBUG") LOG_CONSOLE = os.getenv("LOG_CONSOLE", "true") LOG_FILE = os.getenv("LOG_FILE", "true") LOG_FORMAT = os...
Python
1
, chain.height()); } #[test] fn cannot_forge_difficulty() { let min_difficulty = Difficulty::min_difficulty(); let (_nonce, mut block, chain) = init_decapitated_chain(); block.difficulty = Arc::new(min_difficulty.clone()); assert!(Chain::expand(&chain, block).is_err()); ...
Rust
0
Ok(suitable_vaults[idx].clone()) } } /// Get all vaults below the premium redeem threshold /// Checks three conditions: /// 1. the vault must have tokens issued /// 2. the vault must be available to redeem tokens (not all issued tokens currently bein part of redeem/replace proce...
Rust
0
d_pool_size = updated_round.pool_size; updated_round.pool_size = Uint128(0); } tier1_rounds_store.set_at(tier1_rounds_store.len()-1,&updated_round); //send trigger fee to triggerer transfer_result = transfer_msg( triggerer_address.clone(),...
Rust
0
import click import subprocess import os @click.command('test', help="Runs pytest on the blueprints directory or a specific module.") @click.argument('module_name', required=False) @click.option('-k', 'keyword', help="Only run tests that match the given substring expression.") def test(module_name, keyword): base...
Python
1
ester::{Module, Storage, Call, Event}, // EXCHANGE Exchange: module_exchange::{Module, Storage, Call, Event<T>}, // Mintx AuctionManager: module_auction_manager::{Module, Storage, Call, Event<T>, ValidateUnsigned}, Lend: module_lend::{Module, Storage, Call, Event<T>}, Mintx: module_mintx::{Module, Storage...
Rust
0
line chunks. use crate::{ consts::{CYCLE_MARKER, ONCE_ONLY_MARKER, SEQUENCE_SEPARATOR, SHUFFLE_MARKER}, error::parse::line::LineErrorKind, line::{ parse::{parse_chunk, split_line_at_separator_braces}, Alternative, AlternativeBuilder, AlternativeKind, }, }; /// Parse an `Alternative` o...
Rust
0
n"] pub mod pcr; #[doc = "GPCLR register accessor: an alias for `Reg<GPCLR_SPEC>`"] pub type GPCLR = crate::Reg<gpclr::GPCLR_SPEC>; #[doc = "Global Pin Control Low Register"] pub mod gpclr; #[doc = "GPCHR register accessor: an alias for `Reg<GPCHR_SPEC>`"] pub type GPCHR = crate::Reg<gpchr::GPCHR_SPEC>; #[doc = "Globa...
Rust
0
32 = 101; pub const DEFAULT_REPORT_LATENCY: u32 = 1000; pub trait Trait: SystemTrait { /// Something which can be notified when the timestamp is set. Set this to `()` /// if not needed. type OnFinalizationStalled: OnFinalizationStalled<Self::BlockNumber>; /// The number of recent samples to keep from this chain. D...
Rust
0
main() { let cave = parse_cave(include_str!("../input.txt")); // a cache of the cave's erosion levels let mut cache = HashMap::new(); // force the caching of the rectangle from (0, 0) to the target // (0, 0) and the target won't be present in the cache, but they don't change the result let (tx...
Rust
0
hSSKJr SSKJr SSKJrJ r SSK J r SSKJr /SQr\\"\5:Xdeg)MapperMapDataPipeShufflerIterDataPipeConcaterMapDataPipeZipperMapDataPipeBatcherMapDataPipeSequenceWrapperMapDataPipeBatcherConcaterMapperSequenceWrapperShu...
Python
1
_mix(agg_noise, speech, i) return agg_noise @register_audio_waveform_transform("sporadicnoiseaugment") class SporadicNoiseAugmentTransform(NoiseAugmentTransform): @classmethod def from_config_dict(cls, config=None): _config = {} if config is None else config return cls( _co...
Python
1
from fastapi import APIRouter, Depends from loguru import logger from sqlalchemy.orm import Session from starlette.responses import RedirectResponse from telegram_bot.database import crud from telegram_bot.database.database import get_db, get_db_session from telegram_bot.settings import aio_lru_cache_1h, settings rou...
Python
1
ing.DEBUG) component = os.getenv('INSTANCE', 'triggerflow-controller') # Make sure we log to the console stream_handler = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s.%(msecs)03dZ][%(levelname)s][triggerflow] %(message)s', datefmt="%Y-%m-%dT%H:%...
Python
1
rice / 500, 2) # Увеличен срок окупаемости user_ids = message.from_user.id bot.send_message( message.chat.id, text=( "Вы выбрали карту **RTX 3070**\n\n" "🔹 **Характеристики и стоимость:**\n" "💰 Доход: 500 вив/мес\n" f"💵 Стоимость: {price:.3f} вив\n" f"⏳ Окупае...
Python
1
Device}; <reponame>jamesmahler/knitting_parser<gh_stars>1-10 //! Holds the definition and details for the supported stitches /// The supported stitches #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] pub enum Stitch { // Single K, P, K2Tog, P2Tog, Ssk, Ssp, SlKwise, SlPwise, ...
Rust
0
d = samplesPerClass else: k_corrected = num_samples2select_class top_clean_class_relative_idx = torch.topk(discrepancy_class, k=int(k_corrected), largest=False, sorted=False)[1] agreement_measure[idx_class[top_clean_class_relative_idx]] = 1.0 selected_examples=agreement_me...
Python
1
SubCommand::with_name("-encode") .alias("encode") .about("Encode (compress)") .after_help( "If no input/ output specified reads/ writes from standard input/ output", ) .arg( Arg::with_name...
Rust
0
{ /// Gets the first buckets count, used in MinimizerBucketing phase fn get_second_bucket( hash: <Self as HashFunctionFactory>::HashTypeUnextendable, ) -> BucketIndexType; /// Gets the full minimizer fn get_full_minimizer( hash: <Self as HashFunctionFactory>::HashTypeUnextendable, ...
Rust
0
> { return self.local_vars.as_mut(); } #[inline] pub fn next_pc(&self) -> i32 { return self.next_pc; } #[inline] pub fn set_next_pc(&mut self, next_pc: i32) { self.next_pc = next_pc; } #[inline] pub fn revert_next_pc(&mut self) { self.next_pc = (*se...
Rust
0
Name::Headphones => self.headphones_muted = muted, ChannelName::MicMonitor => self.mic_monitor_muted = muted, ChannelName::LineOut => self.line_out_muted = muted, } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct UsbProductInformation { pub manufacturer_name: Stri...
Rust
0
from datetime import datetime def main(): birthdate = input("Enter your Birthdate Y-m-d: ") def compute_age(birthdate): birth = datetime.strptime(birthdate, "%Y-%m-%d") today = datetime.now() return today.year - birth.year - ((today.month, today.day) < (birth.month, birth.day)) main...
Python
1
__doc__ = """ Cosserat rod module import test""" # System imports if __name__ == "__main__": from pytest import main main([__file__])
Python
1
_stocks['last_purchase'][idx] = last_purchase[idx] idx += 1 return _stocks def change_screen(self, instance): if instance.text == 'Manage Products': self.ids.scrn_mngr.current = 'scrn_product_content' elif instance.text == 'Manage User...
Python
1
[7:0]` to `bit signed [31:0]`. // TODO: Add SBVT SignExtend(usize, &'a Rvalue<'a>), /// Constructor for an array. ConstructArray(HashMap<usize, &'a Rvalue<'a>>), /// Constructor for a struct. ConstructStruct(Vec<&'a Rvalue<'a>>), /// A constant value. Const(value::Value<'a>), ...
Rust
0
EPERM = 1 # Operation not permitted ENOENT = 2 # No such file or directory ESRCH = 3 # No such process EINTR = 4 # Interrupted system call EIO = 5 # I/O error ENXIO = 6 # No such device or address E2BIG = 7 # Argument list too long ENOEXEC = 8 # Exec format error EBADF = 9 # Bad file ...
Python
1
**{}%**", &n.status.description, &n.probability.unwrap_or(-0) ), false, ); e.image( &n.rocket .configuration .image_url .as_ref() .unwrap_or(&PLACEHOLDER.to_string()), ); e.url(&n.vid_urls.get(0).unwrap_or(&V...
Rust
0
eg| fold_digits(digits_trailing_zeros(10), 0i32, 10, neg), true, )) .or(value((0, 0, false))), ) .map( |((mantissa, count, man_overflowed), (exp, _, exp_overflowed))| { ( if man_overflowed { u64::MAX } el...
Rust
0
import torch from torch.nn import functional as F # copy from https://github.com/LeeSinLiang/microGPT/blob/ed40cf9780dbeb180adfe94c227d4aa97e69250e/gpt.py def top_k_top_p_filter(logits: torch.Tensor, top_k: int = 0, top_p: float = 0.0): """ Args: logits (torch.Tensorpe_): 2D tensor with shape (batch, ...
Python
1
# def func1(): # print("你好") # func2() # 不是函数的嵌套. 函数的调用 # # # def func2(): # print("你不好") # # # func1() # def func1(): # print("我是func1") # def func2(): # print("我是func2") # print("我是外面") # func2() # 在func1里面访问func2 # # func1() def func1(): print("func1_before") def fun...
Python
1
th, 'save_weight.pth')) psnr = calc_psnr(bit_inr_res_temp, gt_bits_out_temp) bermax = errors if psnr > psnr_max: psnr_max = psnr if args.save: if args.num_bits == 8: saving_image = (bit_inr_res_temp.detach().cpu().resha...
Python
1
getenv('ARM64', False), "only test for compiled backends, broken on some") class TestNonFloatUOps(TestUOps): def test_neg_int32(self): self._test_uop_fxn(UnaryOps.NEG, lambda a: -a, dtypes.int32) def test_add_int32(self): self._test_bop_fxn(BinaryOps.ADD, lambda a,b: int(a)+int(b), dtypes.int32) def test_sub_int3...
Python
1
mut self) { // CVDisplayLinkStop(_displayLinkRef); // dispatch_suspend(_source); unsafe { CVDisplayLinkStop(self.display_link_ref); dispatch_suspend(self.source) } } // } // // } // @end // // #pragma mark - Callback // // static CVReturn displayL...
Rust
0
'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development :: Compilers', ], packages = [ 'da', 'da.compiler', 'da.examples', 'da.importer', ...
Python
1
import click import sys import mhdata.load as data import mhdata.repair as repair_functions from mhdata.io import DataReaderWriter # Python 3.6 dictionaries preserve insertion order, and python 3.7 added it to the spec officially # Older versions of python won't maintain order when importing data for the build. if s...
Python
1
: SingleQubitGateOperation = input_operation.try_into().unwrap(); let alpha_r = gate.alpha_r(); let alpha_r_param: CalculatorFloatWrapper = CalculatorFloatWrapper::extract(convert_cf_to_pyobject(py, alpha_r)).unwrap(); let method_op = operation.call_method0(py, "alpha_r").unwrap(); let compariso...
Rust
0
import time import torch from torch import nn from d2l import torch as d2l from torch.utils.tensorboard import SummaryWriter def evaluate_accuracy_gpu(net, data_iter, device): if isinstance(net, nn.Module): net.eval() if not device: device = next(iter(net.parameters())).device metri...
Python
1
# # Sử dụng SHA-256 để băm tin nhắn hash_object = hashlib.sha256(message_bytes) # # Lấy giá trị băm dưới dạng chuỗi hex hashed_message = hash_object.hexdigest() # # Gửi giá trị vừa băm cho server prin...
Python
1
from layercake.arithmetic.terms.operations import ProductOfTerms from layercake.arithmetic.terms.operators import OperatorTerm, ComposedOperatorsTerm from layercake.arithmetic.symbolic.operators import Laplacian, D def Jacobian(field1, field2, coordinate_system, sign=1, prefactors=(None, None)): u = coordinate_...
Python
1
now_value); } // 改善してたら必ず採用 if next_value < now_value { return (next, next_value); } // 改善してなくても、tまでは悪化を許容 if (next_value - now_value) < t { return (next, next_value); } (now, now_value) } fn main() { let mut sr = SmallRng::from_entropy(); let unif = Uniform::new...
Rust
0
io::Error> { let name_bytes: &[u8] = name.as_bytes(); let zero_padding_size = compute_padding_size(name_bytes.len()); let mut num_bytes = 0; // Write the number of useful bytes let bytes: [u8; 4] = (name_bytes.len() as i32).to_be_bytes(); num_bytes += out_stream.write(&b...
Rust
0
#[structopt(long, short = "q", default_value = "0", env = "SERVER_GRACE_PERIOD")] /// Defines a grace period in seconds after a `SIGTERM` signal is caught which will delay the server before to shut it down gracefully. The maximum value is 255 seconds. pub grace_period: u8, } <gh_stars>1-10 use std::cell::...
Rust
0
print('"Nexia", "Tiko",\'Damas\', ko\'rganlar qilar havas ') print("5 ning 4-darjasi ",5**4) print("22 ni 4 ga bo\'lganda qoldiq",22%4) print("S= ",125*125 ,"\nP= ",4*125 ) print("S= ",3.14*12**2/4) print((6**2+7**2)**(1/2))
Python
1
UniqueCoveragePoolObservationState; #[no_coverage] fn observe( &mut self, &(index, _counter): &Self::Observation, input_complexity: f64, state: &mut Self::ObservationState, ) { let feature_index = FeatureIdx::new(index); let AnalyzedFeatureRef { least_comple...
Rust
0
the driver development service"), example = "To graph device tree: $ ffx driver dump --graph | dot -Tpng | display" )] pub struct DriverDumpCommand { /// list all device properties. #[argh(switch, short = 'v', long = "verbose")] pub verbose: bool, /// output device graph in dot language so...
Rust
0
VEC4 => Err(UniformWarning::type_mismatch(name, ty)), Type::BVec2 if glty != gl::BOOL_VEC2 => Err(UniformWarning::type_mismatch(name, ty)), Type::BVec3 if glty != gl::BOOL_VEC3 => Err(UniformWarning::type_mismatch(name, ty)), Type::BVec4 if glty != gl::BOOL_VEC4 => Err(UniformWarning::type_mismatch(name, ty...
Rust
0
from_config(config) @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): warnings.warn( "The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use " "`AutoModelForCausalLM` for causal language models...
Python
1
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json from odoo import _, api, models, modules class Users(models.Model): _inherit = 'res.users' @api.model def _get_activity_groups(self): """ Split To-do and Project activities in systray ...
Python
1
import os import cv2 import tensorflow as tf import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout from tensorflow.keras.optim...
Python
1
wrong, it shold be one of ('HumanSegMobile', " "'HumanSegLite', 'HumanSegServer')".format(args.model_type)) model.train( num_epochs=args.num_epochs, train_dataset=train_dataset, train_batch_size=args.batch_size, eval_dataset=eval_dataset, save_interval_epochs=arg...
Python
1
compression options available. fn get_brotli_size(path: &Path) -> u64 { let out = Command::new("brotli") .arg("--best") .arg("--keep") .arg("--stdout") .arg(&path) .output() .expect("Error during brotli"); assert!(out.status.success()); assert!(out.stdout.len...
Rust
0
from BFSDemo import BFS from aStarDemo import aStar from pyamaze import maze,agent,COLOR,textLabel from timeit import timeit ########################### ## Comparison One by One ## # First Run this for BFS: # m=maze(20,30) # m.CreateMaze(loadMaze='mazeComparison1.csv') # bSearch,bfsPath,fwdPath=BFS(m) # l=textLabel...
Python
1
())?; } Format::Toml => { writer.write_all(toml::to_string(&bundle)?.as_bytes())?; } Format::Yaml => { writer.write_all(serde_yaml::to_string(&bundle)?.as_bytes())?; } } Ok(()) } pub fn deserialize_from_...
Rust
0
s_style: Style, pub plus_emph_style: Style, pub plus_non_emph_style: Style, pub minus_line_marker: &'a str, pub plus_line_marker: &'a str, pub commit_style: Style, pub file_style: Style, pub hunk_header_style: Style, pub syntax_set: SyntaxSet, pub terminal_width: usize, pub true_...
Rust
0
g_temp = f'./exps/indoor/evaluation/nvs/evaluation_temp_{lis_name_scenes[0]}.txt' flog_temp = open(path_log_temp, 'w') for i in range(len(vec_stem_eval)): try: flog_temp.write(f'{psnr_imgs_stem[0][i][9:13]} {psnr_imgs_stem[1][i][9:13]} {psnr_imgs_stem[2][i][9:13]}: {psnr_im...
Python
1
not be locked. #[allow(clippy::expect_used)] #[inline] pub fn evolve( input: &Input, voxel_size_sq: &Vec3, time: f64, mut dt: f64, mut values: Array4<f64>, swap: Array4<f64>, ) -> Result<(Array4<f64>, Array4<f64>), Error> { debug_assert!(time > 0.0); debug_assert!(dt > 0.0); // Con...
Rust
0
004; pub const WAVE_FORMAT_1S16: ::DWORD = 0x00000008; pub const WAVE_FORMAT_2M08: ::DWORD = 0x00000010; pub const WAVE_FORMAT_2S08: ::DWORD = 0x00000020; pub const WAVE_FORMAT_2M16: ::DWORD = 0x00000040; pub const WAVE_FORMAT_2S16: ::DWORD = 0x00000080; pub const WAVE_FORMAT_4M08: ::DWORD = 0x00000100; pub const WAVE_...
Rust
0
time.sleep(0.5) update.message.reply_text(f"✅ 语音发送 {success} 人,失败 {fail} 人") def broadcastfull(update: Update, context: CallbackContext): if update.effective_user.id != ADMIN_ID: return if len(context.args) < 2: return update.message.reply_text("用法:/broadcastfull 图片链接 说明") url = contex...
Python
1
Cs |j|S(N(RN(R R((s xmlreader.pytgetValue"scCs |j|S(N(RN(R R((s xmlreader.pytgetValueByQName%scCs||jkrt|n|S(N(RNtKeyError(R ...
Python
1
}) .transpose()? .unwrap_or(10 * 1024); let request_channel_capacity = queries .remove("request_channel_capacity_num") .map(|v| { v.parse::<usize>() .map_err(|_| OptionError::RequestChannelCapacity) }) ...
Rust
0
s' del x84mle9ki07 global pw3uufa_n38 from y55lvj2t2r4 import w_lh6dtecvr as uozde0idn3y, m6f2c2jt8oi, v61_4nbkgho as y87g8uk_s7f, l98rvxahaab as voeq1pgppf3, umr2a2w7f4o, gtk3pmzvx8r as r7vmsb5vwk4 nonlocal cs8wn4778mr import m6bnqxcx1as, m96w4fevp5o as uk20knlg80s, dnpl1wxp1_p, oswhrg29wf2 as mbhx...
Python
1
self.invites.insert(invite); } pub fn remove_invite(&mut self, invite: &Invite) { self.invites.remove(invite); } pub fn remove_user(&mut self, user: &ApiUser) { self.users.remove(user); } } // This enum is used to store the relevant data // of the user in the local storage // I...
Rust
0
= mean_view[in_mask] depths = mean_view[:,2] with prof("build color"): color = self.build_color(means3D=means3D, shs=shs, camera=camera) with prof("build cov3d"): cov3d = build_covariance_3d(scales, rotations) with prof("build c...
Python
1
from randomdict import RandomDict from nose.tools import raises def test_init_with_update(): r = RandomDict({'a':1}) assert 'a' in r def test_len(): r = RandomDict({'a':1}) assert len(r) == 1 def test_delete(): r = RandomDict({'a':1}) del r['a'] assert len(r) == 0 @raises(KeyError) def t...
Python
1
#!/usr/bin/env python3 """ Filter out sentence-pairs whose URLs are not an *exact ordered match*. Example: cat corpus.tsv | ./url_mismatch.py > kept.tsv """ from __future__ import annotations import argparse import re import sys from typing import List, TextIO # RFC-3986ish, scheme is optional URL_REGEX = re.com...
Python
1
#[allow(unused)] pub fn collect_all(&mut self) { self.context.wake(); unsafe { self.context .do_collection(&*self.root, ::std::f64::INFINITY); } } } impl Drop for $arena { ...
Rust
0
BYTES: MultipleMemchr<'static> = MultipleMemchr::new(&[b'<', b'>', b'&', b'\'', b'"']); } let bytes = raw.as_bytes(); if let Some(off) = ESCAPE_BYTES.find(bytes) { let mut result = String::with_capacity(raw.len()); result.push_str(&raw[0..off]); let mut pos = off + 1; ...
Rust
0
, tb_log=tb_log, ckpt_save_dir=ckpt_dir, logger=logger, train_sampler=train_sampler, lr_warmup_scheduler=lr_warmup_scheduler, ckpt_save_interval=args.ckpt_save_interval, ckpt_save_mode=cfg.MODEL.SAVE_MODE, max_ckpt_save_num=args.max_ckpt_save_num, ...
Python
1
arm", target_feature(enable = "v7"))] #[cfg_attr(all(test, target_arch = "arm"), assert_instr(vand))] #[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(and))] pub unsafe fn vandq_u8(a: uint8x16_t, b: uint8x16_t) -> uint8x16_t { simd_and(a, b) } /// Vector bitwise and #[inline] #[target_feature(enable = "...
Rust
0
::<Integer>()) } else { Box::new(users::id) } } fn something_that_is_aggregate<GB>( ) -> Box<dyn BoxableExpression<users::table, Pg, GB, is_aggregate::Yes, SqlType = Nullable<Integer>>> where diesel::dsl::count<users::id>: BoxableExpression<users::table, Pg, GB, is_aggregate::Yes>, { Box::new(d...
Rust
0
#!/usr/bin/env python """Tests the FileParser API """ from tvnamer.files import FileParser from tvnamer.data import EpisodeInfo, DatedEpisodeInfo, NoSeasonEpisodeInfo from helpers import assertType, assertEquals def test_episodeinfo(): """Parsing a s01e01 episode should return EpisodeInfo class """ p = ...
Python
1
import rioxarray as rxr import xarray as xr import geopandas as gpd import numpy as np import sys hdf_file = sys.argv[1] year = sys.argv[2] month = sys.argv[3] day = sys.argv[4] pre_file = rxr.open_rasterio(hdf_file) # translate to geopandas to extract lat/lon from the hdf file's EASE-Grid CRS mid_file = gpd.GeoDat...
Python
1
n("pow", Arity::Fixed(2)).with_params(&[ ParameterBuilder::new("val", ParameterKind::Number), ParameterBuilder::new("power", ParameterKind::Number), ]); const RAND_META: NativeMetaBuilder = NativeMetaBuilder::fun("rand", Arity::Fixed(0)); pub fn declare_math_module(hooks: &GcHooks, module: Gc<Module>) -> StdResul...
Rust
0
class Solution: def videoStitching(self, clips: List[List[int]], T: int) -> int: N = len(clips) memo = {} # Sort the video clips by their starting times clips.sort() # Recursive function def recurse(index, prev_end): ...
Python
1
#[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] ...
Rust
0
size { 1 } } impl<T> Two for T { fn method_two(&self) -> usize { 2 } } impl<T: One + Two> MyTrait for T {} fn main() { let a: &dyn MyTrait = &true; assert_eq!(a.method_one(), 1); assert_eq!(a.method_two(), 2); } // Re-order traits 'One' and 'Two' between compilation // sessions...
Rust
0
from ament_index_python import get_package_share_directory import launch import launch.actions from launch.actions import DeclareLaunchArgument from launch.substitutions import LaunchConfiguration from launch.actions import IncludeLaunchDescription from launch.launch_description_sources import PythonLaunchDescriptionSo...
Python
1
= 45.0f32; let size = glm::vec2(300.0f32, 400.0f32); let color = glm::vec3(0.0f32, 1.0f32,0.0f32); objs.sprite_renderer.draw( objs.face_texture.as_ref(), position, size, rotate, color ...
Rust
0
sales = float(input("Sales: ")) discount_rate = float(input("Discount rate: ")) discount = sales * discount_rate print(f"Discount = ${discount}") tax_rate = float(input("Tax rate: ")) tax = sales * tax_rate print(F"Tax = ${ tax }") total_price = sales - tax + discount print(F"Total price = ${ total_price}")
Python
1
BLOCK_GROUP_DUP => GroupProfile::Dup, BLOCK_GROUP_RAID10 => GroupProfile::Raid10, _ => GroupProfile::Unknown, } } } <gh_stars>0 // Copyright (c) 2018-2021 The MobileCoin Foundation //! Configuration parameters for the MobileCoin Fog View Node use fog_uri::FogViewUri; us...
Rust
0
Vec(vec![ super::Str(b"hello-there".to_vec()) ])])])])])])])])])])])])])])])])])])])])])])])])])])])]) ])])])])])])])])])])])])])])])])])])])])])])])); } #[test] fn test_random() { fn get_random_object<T: Rng>(rng: &mut T, depth: u32) -> TNetStrin...
Rust
0
RSS": round(memory_usage["peak"]["rss"] / 1024 / 1024 * 100) / 100, } print(summary) # Save timeline and events to files with open("memory-usage-timeline.json", "w") as f: json.dump(memory_usage["timeline"], f, indent=2) with open("memory-usage-events.json", "w") as f: json.dump(m...
Python
1
from collections import defaultdict grid = [] with open("data.txt", "r") as file: for line in file.readlines(): grid.append(list(line.strip())) rows, cols = len(grid), len(grid[0]) def find_start_pos(): for x in range(cols): for y in range(rows): if grid[y][x] == "^": ...
Python
1
, AccountId, Balance, Moment> Order<Hash, AccountId, Balance, Moment> { pub fn new( id: Hash, service_id: Hash, customer_id: AccountId, customer_box_public_key: Hash, seller_id: AccountId, dna_sample_tracking_id: Vec<u8>, price: Balance, created_at: Mo...
Rust
0
string(), &portions))?; builder.headers(headers); } _ => unreachable!(), } } Ok(builder.build()) } else { Err(pest_err_pos::<_, Rule>("Missing PEM block", Position::from_start(input)).into()) } } /// Internal helper for mak...
Rust
0
file_path = "%s_attack_non_linf" % (output_path) evaluator.plot_dcf_eer_vs_stat_v1( df, "n_linf", file_path, clean_ref=0, xlabel=r"$L_{\infty}$", log_x=True ) # find the best attacks in terms of linf logging.info("find best attacks from linf point of view") for i in range(len(attack_score_f...
Python
1
pbsdshCommand = "%s %s" % (self.__pbsdsh, args_to_string(arguments)) self.__log.debug("pbsdsh command: %s" % pbsdshCommand) pbsdsh = simpleCommand('pbsdsh', pbsdshCommand, env=self.__env) pbsdsh.start() for i in range(0, 30): status = pbsdsh.exit_code() if status: ...
Python
1
xdf, "SET 3, A", 2, 8, None), Instr::new(0xe0, "SET 4, B", 2, 8, None), Instr::new(0xe1, "SET 4, C", 2, 8, None), Instr::new(0xe2, "SET 4, D", 2, 8, None), Instr::new(0xe3, "SET 4, E", 2, 8, None), Instr::new(0xe4, "SET 4, H", 2, 8, None), Instr::new(0xe5, "S...
Rust
0
M.H2O: 20, M.O2: 5, M.SO2: 0, M.NO2: 8, M.H2S: 7, M.H2SO4: 0, M.HNO3: 0, M.NO: 0, M.HNO2: 0, M.S8: 0, }, { M.H2O: 26.0, ...
Python
1
) } if let Some(s) = &query.gt_iat { f = Box::new(f.and(iat.gt(s))) } // Match also in vicinity. if let Some(s) = &query.sub { let (query_scheme, geo) = validate_sub(s)?; if query_scheme == "geo" { f = Box::new(f.and(scheme.eq(q...
Rust
0
import pytest from unittest.mock import AsyncMock from consumer.consumer import consume_clicks @pytest.mark.asyncio async def test_consume_clicks_with_error(): # Создаем мок для dao mock_dao = AsyncMock() mock_dao.process_message = AsyncMock() mock_dao.insert_batch = AsyncMock() # Создаем мок для ...
Python
1
-8") } fn index(&self,word:&str) -> Option<WordIndex> { let mut low = 0; // values less than this are NOT the word. let mut high = self.number_words; // values equal to or higher than this are NOT the word. while low<high { let mid = (low+high)/2; let word_index...
Rust
0
erman.rs use crate::entity::{mob, MobKind}; use fecs::EntityBuilder; pub struct Enderman; pub fn create() -> EntityBuilder { mob::base(MobKind::Enderman).with(Enderman) } <reponame>pop-os/ecs-disk-manager pub mod create; pub mod info; pub mod luks; pub mod modify; use std::{io, process::ExitStatus}; #[derive(De...
Rust
0
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import logging import sys import json import numpy as np import argparse from sklearn.metrics import accuracy_score,f1_score,recall_score,precision_score def read_answers(filename): answers={} with open(filename) as f: for line ...
Python
1
rmat string: unmatched `}` found } <filename>radius/src/main.rs use crate::processor::Word; use crate::r2_api::hex_encode; use crate::radius::{Radius, RadiusOption}; use boolector::BV; use clap::{App, Arg}; use std::time::Instant; // use crate::state::State; use crate::value::Value; use ahash::AHashMap; type HashMap<...
Rust
0
use ::std as rust_std; // Part of the Crubit project, under the Apache License v2.0 with LLVM // Exceptions. See /LICENSE for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #[ctor::recursively_pinned] #[repr(C)] pub struct SomeStruct { __non_field_data: [crate::rust_std::mem::May...
Rust
0
ition.y = y spawn_point.position.z = z quat = euler2quat(math.radians(roll), math.radians(pitch), math.radians(yaw)) spawn_point.orientation.qx = quat[1] spawn_point.orientation.qy = quat[2] spawn_point.orientation.qz = quat[3] spawn_point.orientation.qw = quat[0] ...
Python
1
# Copyright 2017 The TensorFlow Authors. 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 required by applica...
Python
1