text
string
label_name
string
labels
int64
where F: Fold + ?Sized, { UseName { ident: f.fold_ident(node.ident), } } #[cfg(feature = "full")] pub fn fold_use_path<F>(f: &mut F, node: UsePath) -> UsePath where F: Fold + ?Sized, { UsePath { ident: f.fold_ident(node.ident), colon2_token: Token![::](tokens_helper(f, &node...
Rust
0
ION_IDENTITY_LOC_ID)); assert_ok!(LogionLoc::close(Origin::signed(LOC_OWNER1), LOGION_IDENTITY_LOC_ID)); assert_ok!(LogionLoc::create_logion_transaction_loc(Origin::signed(LOC_OWNER1), OTHER_LOC_ID, LOGION_IDENTITY_LOC_ID)); assert_err!(LogionLoc::create_logion_transaction_loc(Origin::signed(LOC_OWNER1), LOC_ID,...
Rust
0
ost'][-1] try: last_acc = self.network_train_info['val_acc'][-2] last_cost = self.network_train_info['val_cost'][-2] except: last_acc = -10 last_cost = 10 * this_cost # first time it will fail because there is only 1 result stored # only reduce L...
Python
1
erive(PartialEq, typed_builder::TypedBuilder, Deserialize, Serialize, Clone, Debug)] #[non_exhaustive] pub struct ReplaceStreamTagsRequest { /// ID of the stream for which tags are to be replaced. #[builder(setter(into))] pub broadcaster_id: types::UserId, } /// Body Parameters for [Replace Stream Tags](su...
Rust
0
icsGuide/#expand=727,1063,4909,1062,1062,1063&text=_mm512_mask_cmpeq_epu32) #[inline] #[target_feature(enable = "avx512f")] #[cfg_attr(test, assert_instr(vpcmp))] pub unsafe fn _mm512_mask_cmpeq_epu32_mask(m: __mmask16, a: __m512i, b: __m512i) -> __mmask16 { _mm512_cmpeq_epu32_mask(a, b) & m } /// Compare packed u...
Rust
0
ing::*; let bytes = &mut bytes; let key = match take_byte(bytes)? { 0x01 => Self::Table(Some(take_string(bytes)?.into())), 0x02 => Self::Index( take_string(bytes)?.into(), take_string(bytes)?.into(), Some(take_value(bytes)?.into()),...
Rust
0
=> { return Self::Keyed; } _ => {} } } } match &s.ast().data { Data::Struct(_) => Self::Kinded, Data::Enum(_) => Self::Keyed, Data::Union(_) => panic!("unsupported"), ...
Rust
0
mainFailed("找不到有效的 TLS 证书") except Exception: logger.exception("replace ingress failed") raise ReplaceAppDomainFailed("未知错误,请稍后重试") class DomainResourceDeleteService: """Delete custom domain related resources""" def __init__(self, env: ModuleEnvironment): self.wl_app =...
Python
1
(cpu_context) => { use ::txkit_core::method::CpuMethod; self.compute_cpu(cpu_context, tgt, params) }, #[cfg(not(feature = "cpu"))] Context::Cpu(_) => Err(Error::ContextNotSupported), } } else { quote! { Context::Cpu(_) =...
Rust
0
ra/canny_condition_image.png" ) else: control_image = load_image( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flux-control-lora/depth_condition_image.png" ) image = self.pipeline( prompt=self.pr...
Python
1
#tuples ''' ¿Qué es una tupla? Una tupla es una estructura de datos inmutable en Python que se usa para almacenar múltiples elementos en un solo objeto. Es similar a una lista, pero no se puede modificar después de ser creada. Esto significa que no puedes agregar, eliminar ni cambiar elementos de una tupla. ¿Cómo se c...
Python
1
b| a.partial_cmp(b).unwrap()); let real_y: Vec<f64> = real_x.iter().map(|x| REAL_M * x + REAL_C).collect(); let observed_y: Vec<f64> = real_y .iter() .map(|y| y + norm_range.ind_sample(&mut rng) as f64) .collect(); (real_x, observed_y) } fn mat_vec_...
Rust
0
match phy.proxy.set_country(&mut phy_req).await { Ok(status) => zx::Status::from_raw(status), Err(e) => { error!("Error sending SetCountry set_country request to phy #{}: {}", phy_id, e); zx::Status::INTERNAL } } } async fn clear_country(phys: &PhyMap, req: fidl...
Rust
0
(peer, PeerInfo::new(true, MAX_SCORE)); } self.compute_weighted_index(); debug!("[state sync] state after: {:?}", self.peers); } pub fn disable_peer(&mut self, peer: &PeerNetworkId) { if let Some(peer_info) = self.peers.get_mut(peer) { peer_info.is_alive = false; ...
Rust
0
print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value, duration)) # Update the events file. summary_str = sess.run(summary_op) summary_writer.add_summary(summary_str, step) step += 1 # Save a checkpoint peri...
Python
1
: {region_stats['middle_belt']:,} wards", f"-- Southern Nigeria: {region_stats['south']:,} wards", f"-- Coverage: All 774 LGAs across 36 states + FCT", "", "-- Top 10 states by ward count:", ]) # Add top states by ward count sorted_states = sorted(state_ward_counts.item...
Python
1
.arg("run") .arg("--") $( .arg($args) )* .current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/tests")) .output() .unwrap(); assert!( output.status.success(), ...
Rust
0
# Copyright 2024 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
nd make it close to a rectangle. let game_size = Point{ x: term_size as usize * 2 - 5, // x should be odd y: term_size as usize - 5 // Buffer compensates for borders and makes it look cleaner }; let mut board = vec![vec![BoardPiece { state: State::Empty, position: 0 }; game_size.x];...
Rust
0
ctive x = torch.tensor([[0.1, 0.6, 2.0], [1.4, 2.0, 3.0]], dtype=torch.float32, requires_grad=True) threshold = torch.tensor([1.0, 1.0, 1.0], dtype=torch.float32, requires_grad=True) bandwith = 1.0 output = jump_relu(x, threshold, rectangle_kernel, bandwith) grad_output = torch.tensor([[1.0, 1.0, ...
Python
1
self.current_state.line_cap = new_line_cap } #[inline] pub fn set_line_join(&mut self, new_line_join: LineJoin) { self.current_state.line_join = new_line_join } #[inline] pub fn set_miter_limit(&mut self, new_miter_limit: f32) { self.current_state.miter_limit = new_miter_l...
Rust
0
import os import subprocess import argparse from tqdm import tqdm def main(base_path, rgb_matrix_file, swir_matrix_file, nir_matrix_file, start_range, end_range): script_path = "undistort.py" # Iterate over the data directories for RGB data for i in tqdm(range(start_range, end_range + 1), desc="Processing...
Python
1
import numpy as np from gymnasium.spaces import Box def check_param(obs_space, min_max_pair): assert np.dtype(obs_space.dtype) == np.dtype("float32") or np.dtype( obs_space.dtype ) == np.dtype("float64") assert ( isinstance(min_max_pair, tuple) and len(min_max_pair) == 2 ), f"range_sca...
Python
1
ER, 'showMovies', 'Page ' + sPaging, oOutputParameterHandler) oGui.setEndOfDirectory() def __checkForNextPage(sHtmlContent): oParser = cParser() sPattern = 'class="next" href="([^"]+)".+?<\/a><a class="last" href="https.+?page\/(\d+)' aResult = oParser.parse(sHtmlContent, sPattern) if aResul...
Python
1
BORTED: asEContextState = 2; pub const asEContextState_asEXECUTION_EXCEPTION: asEContextState = 3; pub const asEContextState_asEXECUTION_PREPARED: asEContextState = 4; pub const asEContextState_asEXECUTION_UNINITIALIZED: asEContextState = 5; pub const asEContextState_asEXECUTION_ACTIVE: asEContextState = 6; pub const a...
Rust
0
////////////////////////////// // Intersects impl<'a, T> Intersects for LineSegmentView<'a, T, 2> where T: PolygonScalar, { type Result = ILineSegment<'a, T>; fn intersect(self, other: LineSegmentView<'a, T, 2>) -> Option<Self::Result> { let a1 = self.min.inner(); let a2 = self.max.inner(); let b1 = ...
Rust
0
mut self) -> Result<()> { let input = document().get_element_by_id("file-input").unwrap(); let files: FileList = js!(return @{input}.files).try_into().unwrap(); match files.iter().nth(0) { None => Err(NoInputFile), Some(ref file) if !file.name().ends_with(".csv") => Err(I...
Rust
0
<gh_stars>1-10 use pipeline::Pipeline; pub fn make_pipeline() -> Pipeline { Pipeline { queue: vec![ ("trimmer-fi".into(), trimmer), ("stopWordFilter-fi".into(), stop_word_filter), ("stemmer-fi".into(), stemmer), ], } } make_trimmer!( "A-Za-z...
Rust
0
, we will access element U(min(N,K+1),max(N,K+1)). Thus, the number of entries in row I is the larger of the maximum number of pulses we will ever allocate for a given N=I (K=128, or however many fit in 32 bits, whichever is smaller), plus one, and the maximum N for which K=I-1 pulses fit in 32 bits. The largest ban...
Rust
0
let mut req: BTreeMap<&str, &str> = BTreeMap::new(); req.insert("env_id", env_id); let instance_id = try!(self.post("/v1/envs/".to_string(), req.to_json())); let instance_id = match instance_id.find("instance_id") { Some(id) => id.as_str().unwrap(), None => panic!("Unrecognized environment i...
Rust
0
)] pub fn disabled(self) -> &'a mut W { self.variant(REGION58_A::DISABLED) } #[doc = "Protection enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(REGION58_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -...
Rust
0
0 - for i.MX508 and i.MX6SL) EPDC_FLAG_USE_DITHERING_Y1 = 0x00_2000, EPDC_FLAG_USE_REMARKABLE_DITHER = 0x30_0f30, EPDC_FLAG_USE_DITHERING_Y4 = 0x00_4000, EPDC_FLAG_USE_DITHERING_ALPHA = 0x3ff0_0000, EPDC_FLAG_USE_DITHERING_BETA = 0x7546_1440, EPDC_FLAG_EXP1 = 0x270_ce20, EPDC_FLAG_EXP2 = 0x2...
Rust
0
""" main page """ from selenium.webdriver.common.by import By from .base_page import BasePage class MainPage(BasePage): def __init__(self, *args, **kwargs): super(MainPage, self).__init__(*args, **kwargs) # def go_to_login_page(self): # link = self.browser.find_element(By.CSS_SELECTOR, "#login...
Python
1
from mlc import utils import os def preprocess(i): os_info = i['os_info'] if os_info['platform'] == 'windows': return {'return': 1, 'error': 'Windows is not supported in this script yet'} env = i['env'] automation = i['automation'] logger = automation.logger recursion_spaces = i[...
Python
1
sat/kWU. // All the transactions' feerate MUST be below `target_feerate`. fn cpfp_package( revaultd: &Arc<RwLock<RevaultD>>, bitcoind: &BitcoinD, to_be_cpfped: Vec<ToBeCpfped>, target_feerate: u64, ) -> Result<(), BitcoindError> { let revaultd = revaultd.read().unwrap(); let cpfp_descriptor = &...
Rust
0
metadata={'short_squeeze_risk': 0.7} ) ] } market_data = { 'volatility': 0.25, 'trend_strength': 0.3, 'volume_ratio': 1.5 } print("⚡ Processing highly conflicting signals for AMZN...") print("\nInput Signals:") for signal in con...
Python
1
log: [0; 256], }; let mut tmp = 1; for power in 0..255usize { tabs.exp[power] = tmp; tabs.log[tmp as usize] = power as u8; tmp = xtimes(tmp); } tabs.exp[255] = 1; match write!(file, "{}", tabs) { Ok(()) => {} Err(_) => panic!("Could not format the table...
Rust
0
se) scores = util.cos_sim(model.encode(query, convert_to_tensor=True), section_embeddings)[0].cpu().tolist() GENERIC_TITLES = {"introduction", "overview", "summary", "conclusion"} for sec, score in zip(all_sections, scores): if sec['title'].lower().strip() in GENERIC_TITLES: sec['score'...
Python
1
This indicated timeout waiting for messages. In such case, we end // the actor proxy let _ = sender.send(ActorProxyCommand::End).await; } } } }); }); } /// The Chain Specification name. pub const CHAIN_SPEC_NAME...
Rust
0
from collections import defaultdict, deque import datetime import pickle import time import errno import os import torch import torch.distributed as dist class SmoothedValue(object): """Track a series of values and provide access to smoothed values over a window or the global series average. """ def ...
Python
1
"); let mut count = 0; while let Some(Ok((i, sum))) = results.next() { assert_eq!(sum, (0..i + 1).reduce(|a, b| a + b).unwrap()); count += 1; } assert_eq!(count, 2000); } #[test] fn reduce_by_key_test() { let mut conf = JobConf::new("reduce_by_key_test"); conf.set_workers(2); ...
Rust
0
omated conflict resolution process. Occurring unresolvable conflicts are stored in *unresolved_conflicts*. """ try: self.resolver.resolve_conflicts(self.first_patches, self.second_patches, self.co...
Python
1
The gas limit for the contract instantiation. #[inline] pub(crate) fn gas_limit(&self) -> u64 { self.gas_limit } /// The endowment for the instantiated contract. #[inline] pub(crate) fn endowment(&self) -> &E::Balance { &self.endowment } /// The raw encoded input data....
Rust
0
from telegram import Update, InlineKeyboardMarkup, CallbackQuery from telegram.ext import ( ConversationHandler, CallbackQueryHandler, MessageHandler, ContextTypes, filters, ) from CTVM_bot.restaurant_data_manager import RestaurantDataManager from CTVM_bot.shared_buttons import SharedButtons # Def...
Python
1
from ansible import utils, errors import os import xml.etree.ElementTree as etree class LookupModule(object): def __init__(self, basedir=None, **kwargs): self.basedir = basedir def tostr(self, node): if isinstance(node, etree._Element): if len(node.getchildren()) == 0: ...
Python
1
def solution(bandage, health, attacks): answer = 0 bandtime, heal, bonus = bandage last_time = attacks[-1][0] time = 0 max_health = health combo = 0 is_attacked = False while True: time += 1 # 공격당함 for a in attacks: if time == a[0]: #...
Python
1
y.lazy('circuits.graphql.types')], Annotated["VirtualCircuitType", strawberry.lazy('circuits.graphql.types')], ], strawberry.union("CircuitGroupAssignmentMemberType")] | None: return self.member @strawberry_django.type( models.VirtualCircuitType, fields='__all__', filters=VirtualCircui...
Python
1
septett_idx + 1 { panic!("Source must be one byte larger than destination"); } let septett = src[septett_idx]; for (idx, dst_b) in dst.iter_mut().enumerate() { let b = src[idx]; let mask = if (septett & (1 << idx)) != 0 { 0x80 } else { 0x00 }...
Rust
0
ESSOR_PERFSTATE_POLICY, 0xbbdc3814, 0x18e9, 0x4463, 0x8a, 0x55, 0xd1, 0x97, 0x32, 0x7c, 0x45, 0xc0} DEFINE_GUID! {GUID_PROCESSOR_PERF_INCREASE_THRESHOLD, 0x06cadf0e, 0x64ed, 0x448a, 0x89, 0x27, 0xce, 0x7b, 0xf9, 0x0e, 0xb3, 0x5d} DEFINE_GUID! {GUID_PROCESSOR_PERF_INCREASE_THRESHOLD_1, 0x06cadf0e, 0x64ed, 0x448a, 0x89, ...
Rust
0
-> Self { let max_texture_size = unsafe { (glow::MAX_TEXTURE_SIZE - 1).min(gl.get_parameter_i32(glow::MAX_TEXTURE_SIZE) as u32) }; CanvasCaps { max_texture_size } } } #[derive(Debug, Clone)] pub enum CanvasSizeConfig { LogicalSize(Vector2<u32>), Fill, } pub struct Can...
Rust
0
ive::StTermTrait as TermTrait; pub use sept_derive::StTypeTrait as TypeTrait; #[cfg(all(test, feature = "subtle"))] mod test { use cryptographer::subtle; use vendored_rand as rand; fn random_bytes() -> (Vec<u8>, Vec<u8>) { let ell = (rand::random::<u8>() as usize) + 1; let mut x = vec![0u8...
Rust
0
(i64: 0, 32, 1024, ru_i64_0_32_1024) (isize: 0, 32, 1024, ru_isize_0_32_1024) } macro_rules! range_inclusive { ($(($t: ty: $mean: expr, $std_dev: expr, $length: expr, $width: expr, $name: ident))*) => ($( #[test] fn $name() { let mut bin = Unimodal::new(); let input: Vec<$t> = rand_outliers($m...
Rust
0
from chatmof.tools.search_csv.tool import _get_search_csv __all__ = ["_get_search_csv"]
Python
1
file), ) { tags_clone .lock() .unwrap() // Safe assuming no poisoning .entry(tag.label.clone()) .or_insert_with(Vec::new) .push(tag.clone()); } ...
Rust
0
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modi...
Python
1
import json import re from typing import List, Set, Tuple from pyquery import PyQuery from requests.models import Response from ..utils import printError, writeFailLog def selectTag(response: Response) -> List[str]: """[summary] url: https://www.pixiv.net/artworks/xxxxxx collect all image tags from (artw...
Python
1
seString::from, ), )), remove_empty_string_parsed, ), )), |(key, val)| Parameter { key, val }, )(input) } // parameter list #[test] pub fn parse_parameter_list() { assert_parser!( parameters, ";KEY=VALUE", v...
Rust
0
import numpy as np import sys sys.path.append('../') from paths import ML_Path sys.path.append(ML_Path) from utilities import Utilities class Polynomials(Utilities): def model_poly(self,x,theta): y = np.zeros_like(x) for p in range(len(theta)): y += theta[p]*x**p return y d...
Python
1
seconds => "mikrosekund", Milliseconds => "millisekund", Seconds => "sekund", Minutes => "minut", Hours => "timme", Days => "dag", Weeks => "vecka", Months ...
Rust
0
""" Main BaiduDriver client interface Based on TIP 0: Overall Architecture Design Zero-configuration Baidu NetDisk authorization SDK """ import time import asyncio from threading import Thread from contextlib import contextmanager from typing import Any, Callable, Dict, List, Optional, Union from .auth import AuthMan...
Python
1
`Ipv4Addr` doesn't implement `UnicastAddress`. // // TODO(joshlf): Support unnumbered interfaces. Once we do that, a few // issues arise: A) Does the unicast restriction still apply, and is that // even well-defined for IPv4 in the absence of a subnet? B) Presumably we // have to always bind to a p...
Rust
0
planus; pub mod planus_api; pub mod planus_test; pub mod hexdump; mod unit_tests; #[cfg(test)] pub mod tests { use std::path::Path; use anyhow::Result; pub fn compare_regenerate_file( path: impl AsRef<Path>, new_val: &[u8], should_regenerate: bool, ) -> Result<()> { ...
Rust
0
from_values.get(key) { if from_mil.is_none() && mil.is_none() { continue; } if let Some(from_mil) = from_mil { if let Some(mil) = mil { if let Some(diff) = get_...
Rust
0
idateISO): templatemacroFile = open(macroIsol, 'r') isolmacroFile = open(isolcfgFileName+'.C' , 'w' ) replace(replace_map_ISOL, templatemacroFile, isolmacroFile) if(Submit): os.system('root -b -q -l '+ cfgFileName+'.C'+ '> macro.'+cfgFileName+'.log') ...
Python
1
ing': msg_type = col.Color(col.YELLOW, msg_type) elif msg_type == 'error': msg_type = col.Color(col.RED, msg_type) elif msg_type == 'check': msg_type = col.Color(col.MAGENTA, msg_type) return '%s: %s,%d: %s' % (msg_type, fname, line, msg) def CheckPatches(verbose, args): '''Run ...
Python
1
(&path.0).unwrap(); do_bulk_load(&store, &data); }) }); } { let mut data = Vec::new(); read_data("explore-10000.nt.zst") .read_to_end(&mut data) .unwrap(); let mut group = c.benchmark_group("store load large"); group.t...
Rust
0
e-sized length prefix tag @ 0x81..=0x84 => { let nbytes = tag.checked_sub(0x80).ok_or(ErrorKind::Overlength)? as usize; debug_assert!(nbytes <= 4); let mut decoded_len = 0; for _ in 0..nbytes { decoded_len = (decoded_len <<...
Rust
0
KeypadOctal => bind::SDL_SCANCODE_KP_OCTAL, KeypadDecimal => bind::SDL_SCANCODE_KP_DECIMAL, KeypadHexadecimal => bind::SDL_SCANCODE_KP_HEXADECIMAL, LCtrl => bind::SDL_SCANCODE_LCTRL, LShift => bind::SDL_SCANCODE_LSHIFT, LAlt => bind::SDL_SCANCODE_LALT, ...
Rust
0
# This file is MACHINE GENERATED! Do not edit. # Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. """Public API for tf._api.v2.saved_model.main_op namespace """ import sys as _sys from tensorflow.python.saved_model.main_op_impl import main_op # line: 30 from tensorflow.python.saved_...
Python
1
#!/usr/bin/env python """ Python macro tool. Expands macros in C++ code using the python interpreter. Example: /* <<<PYMACRO print("const int table[] = {") print(" " + ", ".join(str(i) for i in range(8))) print("};") >>> */ const int table[] = { 0, 1, 2, 3, 4, 5, 6, 7 }; /* <<<PYMACROEND>>> */ """ import sy...
Python
1
(Input, Option<PathBuf>) { } fn some_inpu(&mut self, input: Input, input_path: Option<PathBuf>) -> (Input, Option<PathBuf>) { } } // #1843 #[allow(non_snake_case)] pub extern "C" fn Java_com_exonum_binding_storage_indices_ValueSetIndexProxy_nativeContainsByHash( ) -> bool { false } <reponame>vagrod/z...
Rust
0
run2 到 run1,其实就是更新 run1 的参数并删除 run2, // run1 下标不变,但合并后长度是 run1 和 run2 长度之和 runs.remove(pos2); runs[pos1] = Run { pos: run1.pos, len: run1.len + run2.len, }; // 取出合并后的 run1 去进行归并排序 let new_list = self.list ...
Rust
0
onA > lon0 == lonB > lon0, // i.e. !(lonA > lon0 != lonB > lon0). // A | B (lon0 <= lonB) || (lonA < lon0) // --]++|++]-- // B | A (lon0 <= lonA) || (lonB < lon0) // // So the previous code was bugged in this very specific case: // - `lon0` has the same value as a vertex being part o...
Rust
0
copy_dst_barrier = ImageBarrierCI::new(glyphs_image, image_range) .access_mask(vk::AccessFlags::empty(), vk::AccessFlags::TRANSFER_WRITE) .layout(vk::ImageLayout::UNDEFINED, vk::ImageLayout::TRANSFER_DST_OPTIMAL); let shader_read_barrier = ImageBarrierCI::new(glyphs_image, image_range) .acc...
Rust
0
#!/usr/bin/env pythonrunscript # # Defines and serves an idleclicker game # # Just run me with pythonrunscript, and I will auto-install # my dependencies and serve on port 8090 # # /// pythonrunscript-requirements-txt # python-fasthtml>=0.6.9,<0.7 # uvicorn>=0.29 # python-multipart # sqlite-utils # requests # replicate...
Python
1
# if a mask is all True(all background), then set it all False. mask_sum = (attn_mask.sum(-1) != attn_mask.shape[-1]).unsqueeze(-1) attn_mask = attn_mask & mask_sum # attn_mask = torch.zeros_like(attn_mask).bool() attn_mask = None # cross_attn + se...
Python
1
key=lambda x: x['order']) # total_optimization_time = matrix_time + tsp_time # logger.info(f'Trip {trip_id} optimization completed successfully in {total_optimization_time:.3f} seconds total') # print(f"Total optimization time: {total_optimization_time:.3f} seconds (Matrix: {matrix_time:.3f}s, ...
Python
1
from django.urls import path from . import views from .views import index, about urlpatterns = [ path("", index, name='index'), path("index/", index, name='index'), path("about/", about, name='about'), path('dice/<int:n>/', views.dice, name='dice'), path('heads_tails/<int:n>/', views.heads_tails...
Python
1
Content-Type: application/octet-stream\r\n\r\n" ) .unwrap(), FieldHeaders { name: "field".into(), content_type: Some(mime::APPLICATION_OCTET_STREAM), ..FieldHeaders::default() } ); assert_eq!( parse_headers( b...
Rust
0
"main.css"), "main-css") .expect("Failed to create main.css."); let body = document.body().unwrap(); let outer_div : HtmlElement = document.create_element("div") .unwrap().unchecked_into(); outer_div.set_id("outer-div"); body.append_child(&outer_div).ok(); let common_div : HtmlEl...
Rust
0
addr: &SockAddr) -> MioResult<()> { nix::bind(io.fd, &from_sockaddr(addr)) .map_err(MioError::from_sys_error) } pub fn listen(io: &IoDesc, backlog: usize) -> MioResult<()> { nix::listen(io.fd, backlog) .map_err(MioError::from_sys_error) } pub fn accept(io: &IoDesc) -> MioResult<IoDesc> { ...
Rust
0
params = None else: raise Exception(f"Unknown content type '{content_type}'") if inspect.signature(pyfunc_model.predict).parameters.get("params"): raw_predictions = pyfunc_model.predict(df, params=params) else: _log_warning_if_params_not_in_predict_signature(_logger, params) ...
Python
1
{ if curr.word_count <= 40 { if next.word_count > 17 { res.push_str(curr.as_text()); } } else { res.push_str(curr.as_text()); } } } } // for last block if...
Rust
0
eycode: Keycode) { self.keyboard_states.insert(keycode, true); } pub fn process_keyup(&mut self, keycode: Keycode) { self.keyboard_states.insert(keycode, false); match keycode { Keycode::Space => { self.inputs.push(GameInput::Jump) } ...
Rust
0
''' Modified from SparseConvNet data preparation: https://github.com/facebookresearch/SparseConvNet/blob/master/examples/ScanNet/prepare_data.py ''' import glob, plyfile, numpy as np, multiprocessing as mp, torch, json, argparse import os import scannet_util # Map relevant classes to {0,1,...,19}, and ignored classe...
Python
1
fn as_raw_BFMatcher(&self) -> *const c_void { self.inner_as_raw() } } impl crate::features2d::BFMatcherTrait for PtrOfBFMatcher { #[inline] fn as_raw_mut_BFMatcher(&mut self) -> *mut c_void { self.inner_as_raw_mut() } } impl core::AlgorithmTraitConst for PtrOfBFMatcher { #[inline] fn as_raw_Algorithm(&self...
Rust
0
elf } } #[repr(C)] #[doc = "*Required features: `\"Win32_UI_Shell\"`, `\"Win32_Foundation\"`, `\"Win32_UI_WindowsAndMessaging\"`*"] #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_WindowsAndMessaging"))] pub union NOTIFYICONDATAA_0 { pub u...
Rust
0
from commands.Base_Command import BaseCommand from core.application_data import ApplicationData from models.vehicles import Scania, Actros, Man class AssingTruck(BaseCommand): def __init__(self, params: list[str], app_data: ApplicationData): super().__init__(params, app_data) def execute(self): ...
Python
1
from django.conf import settings from factory import Faker, SubFactory from wagtail_factories import PageFactory from foundation_cms.legacy_apps.donate.models import DonateLandingPage from foundation_cms.legacy_apps.utility.faker import StreamfieldProvider from foundation_cms.legacy_apps.utility.faker.helpers import r...
Python
1
) @staticmethod def _process_time_range( time_range: str | None, filters: list[QueryObjectFilterClause] | None = None, columns: list[Column] | None = None, ) -> str: if time_range is None: time_range = NO_TIME_RANGE temporal_flt = [ ...
Python
1
have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for ComputeLimitsUnitType { fn from(s: &str) -> Self { match s { "InstanceFleetUnits" => ComputeLimitsUnitType::InstanceFleetUnits, "Instances" => ComputeLimitsUnitType::Instances, ...
Rust
0
part_1_answer = part_1(&input_str); println!("Part 1: {}", part_1_answer); let part_2_answer = part_2(&input_str); println!("Part 2: {}", part_2_answer); } fn part_1(input_str: &str) -> i32 { let mut frequency = 0; for line in input_str.lines() { let delta_frequency: i32 = line.parse().un...
Rust
0
from rest_framework import serializers from reports.models import TestInstance class TestInstanceSerializer(serializers.ModelSerializer): id = serializers.IntegerField(label="id") name = serializers.CharField(source="test.name", read_only=True, label="test name") test_id = serializers.CharField(label="te...
Python
1
z_array"] = nn.utils.rnn.pad_sequence( batch["mz_array"], batch_first=True, ) batch["intensity_array"] = nn.utils.rnn.pad_sequence( batch["intensity_array"], batch_first=True, ) return batch def _tensorize(obj: Any) -> Any: # noqa: ANN401 """Turn lists into tensor...
Python
1
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved. import random import re from odoo import api, fields, models, _ from odoo.exceptions import UserError """ account.move object: add support for Be...
Python
1
""" The name of this module, right now, is a lie. It actually selects points as close as possible to the cross section that you select using nearest neighbour. """ import xarray as xr import nearest_neighbour as nn import numpy as np import numpy.typing as npt def linear_equation_from_points(lat_init, lat_end, lon_i...
Python
1
tumn(tens) >> filtered (427, 640, 3) """ return _autumn_process(tens) ## ROI:(top-left x1,y1, bottom-right x2,y2), shadow_dimension=no. of sides of polygon generated def sim_shadow( tens: Tensor, num_shadows : int = 1, rectangular_roi : Tuple = (-1,-1,-1,-1), ...
Python
1
nfig) -> Context { let resolver = create_resolver(config.get_dns_config()); Context { config, dns_resolver: Arc::new(resolver), dns_query_cache: None, } } pub fn new_dns(config: Config) -> Context { let resolver = create_resolver(config.get_dn...
Rust
0
Specialization, pub minor_skill_1: Skill, pub major_skill_1: Skill, pub minor_skill_2: Skill, pub major_skill_2: Skill, pub minor_skill_3: Skill, pub major_skill_3: Skill, pub minor_skill_4: Skill, pub major_skill_4: Skill, pub minor_skill_5: Skill, pub major_skill_5: Skill, ...
Rust
0
is_obj_shorthand: fv.is_shorthand(), }, }) }); atoms.sort_by_key(|r| r.range.start); Some((atoms, has_local_ref)) } /// Atom's property records if it is param identifier fn break_down_fn_params(&self, raw: &'a str) -> Option<Vec<Atom<bool...
Rust
0