text
string
label_name
string
labels
int64
upper bound on the compressed size for `compress()`. pub fn compress_bound(source_len: usize) -> usize { (unsafe { raw::compressBound(source_len as c_ulong) }) as usize } pub fn compress_vec(source: &[u8]) -> Result<Vec<u8>, Error> { let upper_bound = compress_bound(source.len()); let mut dest = Vec::with...
Rust
0
size, concat!( "Offset of field: ", stringify!(HAL_JoystickButtons), "::", stringify!(count) ) ); } #[repr(C)] #[derive(Copy, Clone)] pub struct HAL_JoystickDescriptor { pub isXbox: u8, pub type_: u8, pub name: [::std::os::raw::c_char; 256u...
Rust
0
tribute is only used internally and never mixed with regular fields. Types or values of private attrs are not checked by pydantic and it's up to you to keep them relevant. Private attrs are stored in model __slots__. :param default: the attribute’s default value :param default_factory: callable that ...
Python
1
SWHSDST {} #[doc = "`write(|w| ..)` method takes [swhsdst::W](swhsdst::W) writer structure"] impl crate::Writable for SWHSDST {} #[doc = "Channel Software handshake Destination Register"] pub mod swhsdst; #[doc = "Channel Block Transfer Resume Request Register\n\nThis register you can [`read`](crate::generic::Reg::rea...
Rust
0
qutive """ if not l: return False if l[0] != start: return False if l[-1] != end: return False # for consequtiveness, look at the integers in pairs pairs = zip(l, l[1:]) if not all([p[0]+1 == p[1] for p in pairs]): return False return True def try_port(por...
Python
1
ND_CARRY, }; pub const BITMASK: u16 = 0b11; pub const BIN_ZERO: u16 = 0b00; pub const BIN_POS: u16 = 0b01; pub const BIN_INVALID: u16 = 0b10; pub const BIN_NEG: u16 = 0b11; pub const CHAR_ZERO: char = '0'; pub const CHAR_POS: char = '1'; pub const CHAR_INVALID: char = '?'; pub const CHAR_NEG: char = 'T'; #[derive(C...
Rust
0
# for _ in range(5): # print("*") f""" reading files parsing """ file = open("hello.txt",'r') content=file.read() print(content) # content=file.readlines() # for i in content: # print(i) # print(content.find('name')) # # print(content.find('name'):len ) # print(file)
Python
1
import torch import torch.nn as nn # from einops import rearrange class CodingRate(nn.Module): def __init__(self, eps=0.01): super(CodingRate, self).__init__() self.eps = eps def forward(self, X): #normalize over the dim_heads dimension ''' X with shape (b, h, m, d) ...
Python
1
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from create import User, Item, Bid engine = create_engine('postgresql://localhost:5432/tbay') Session = sessionmaker(bind=engine) session = Session() Base = declarative_base() bidder1...
Python
1
)], [LilyWhite, "Lily white", 348, (237, 234, 234)], [Seashell, "Seashell", 349, (233, 218, 218)], [Burgundy, "Burgundy", 350, (136, 62, 62)], [Cork, "Cork", 351, (188, 155, 93)], [Burlap, "Burlap", 352, (199, 172, 120)], [Beige, "Beige", 353, (202, 191, 163)], [Oyster, "Oyster", 354, (187, ...
Rust
0
me__=='__main__': # Setup the 2 contexts. sspiclient=ClientAuth("NTLM") sspiserver=ServerAuth("NTLM") # Perform the authentication dance, each loop exchanging more information # on the way to completing authentication. sec_buffer=None while 1: err, sec_buffer = sspiclient.authori...
Python
1
); } } } else { let position = self.position(c_width, c_height, text_width, font_height); render_line( &self.text, 0, position, (text_width, font_height), scale_factor, ...
Rust
0
pub struct GtkListBoxAccessible { pub parent: GtkContainerAccessible, pub priv_: *mut GtkListBoxAccessiblePrivate, } impl ::std::fmt::Debug for GtkListBoxAccessible { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GtkListBoxAccessible @ {:?}", self as ...
Rust
0
import triton, torch import triton.language as tl from torch.cuda.amp import custom_fwd @triton.jit def _flash_decoding_stage1_kernel( Q, K, V, qk_scale, b_req_tokens_table, B_Seqlen, num_kv_groups, # group of kv heads Mid_O, Mid_O_LogExpSum, stride_req_to_tokens_b, stride...
Python
1
#!/usr/bin/env python3 from flask import Flask, request, abort, render_template_string import os.path app = Flask(__name__) @app.route('/', methods=['GET']) def index(): name = request.args.get('name') if name is not None: return render_template_string(open('templates/hello.html').read().format(name=...
Python
1
ame) -> Dict[str, torch.Tensor]: """ Parameters ---------- seq_df: pd.DataFrame with at least two columns `ID` and `sequence` Returns ------- dict with ID as keys and embeddings as values. Embeddings are pytorch tensor with shape (#sequences, length of s...
Python
1
# -*- coding: utf-8 -*- # MinIO Python Library for Amazon S3 Compatible Cloud Storage, # (C) 2020 MinIO, 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/lic...
Python
1
# by @npdkdev import logging import os from distutils.util import * from dotenv import load_dotenv from logging.handlers import RotatingFileHandler load_dotenv(".env") BOT_TOKEN = os.environ.get("BOT_TOKEN", "") API_ID = int(os.environ.get("API_ID", "")) API_HASH = os.environ.get("API_HASH", "") PORT = int(os.enviro...
Python
1
close_prices = [] # 使用最后的 n_steps 天数据作为初始输入 current_input_pctchg = pctchg_scaled[-n_steps:] current_input_open_pctchg = open_pctchg_scaled[-n_steps:] for _ in range(future_days): current_input_pctchg = current_input_pctchg.reshape((1, n_steps, 1)) predicted_pctc...
Python
1
: &<Self as OptionDiscriminant>::NONE_DISCRIMINANT_BYTES, }, fields: &[], }, Variant { name: "Some", discriminant: Discriminant { big_endian_bytes: &<Self as OptionDiscriminant>::SOME_...
Rust
0
tent_load(self, id_): m = our_ids.match(str(id_)) if not m: return None else: type_, args = m.group(1, 2) if type_ == "attribute": key, clsarg = args.split(":") cls = pickle.loads(b64decode(clsarg)) return getatt...
Python
1
impl Scanner for EmailScanner { fn scan(&self, s: &str, at: usize) -> Option<Range<usize>> { if let Some(start) = self.find_start(&s[0..at]) { let after = at + 1; if let Some(end) = self.find_end(&s[after..]) { let range = Range { start: start, ...
Rust
0
each level and draw the windows for level in range(0, len(lanes_centroids)): # Window_mask is a function to draw window areas center_y = lanes_centroids[level][2] l_mask = self.window_mask(self.window_width, self.window_height, img, lanes_centroids[level][0], center_y) ...
Python
1
](trait.Prob.html#method.lnprob) can be seen in the source code. pub trait Prob { /// Computes the natural logarithm of the likelihood of a position in parameter space fn lnlike(&self, params: &Guess) -> f64; /// Computes the natural logarithm of the prior probability of a position in parameter space f...
Rust
0
seeds are highly uncorrelated. # # The reason for this procedure is that when we use multiple processes to build # our images, we want to make sure that the results are deterministic regardless # of the way the objects get parcelled out to the different p...
Python
1
_event_subscribers: callback(event) def deprecated_event_fire_on_mount(self, tree): self.deprecated_event_fire_on_lifecycle(DeprecatedLifecycleEvent("mount", tree)) def deprecated_event_fire_on_unmount(self, tree): self.deprecated_event_fire_on_lifecycle(DeprecatedLifecycleEvent("u...
Python
1
one/element-lib.htm#prettyprint i = "\n" + level * " " if len(element): if not element.text or not element.text.strip(): element.text = i + " " if not element.tail or not element.tail.strip(): element.tail = i for element in element: ...
Python
1
let offset = parent_offset + offset as usize; let format = b.read::<u16>(offset + 4)?; if format != 0x8000 { return None; } let outer = b.read::<u16>(offset)?; let inner = b.read::<u16>(offset + 2)?; Some([outer, inner]) } fn read_anchor(&self, o...
Rust
0
ame]); } if output.is_empty() { output.add_row(row![H3 -> "No results"]); } output.printstd(); } } Ok(()) } <gh_stars>0 extern crate glfw; use glfw::{Action, Context, Key}; fn main() { let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).u...
Rust
0
cursor.execute("INSERT INTO TrafficManager (userID) VALUES (%s)", (userID,)) name, position, phone, managed_city_id = register_traffic_manager() cursor.execute( "INSERT INTO TrafficManager (userID, name, position, phone, managedCityID) VALUES (%s, %s, ...
Python
1
server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT, ssl_version=ssl.PROTOCOL_TLSv1_1) self._assert_connection_success(server, ca_certs=SERVER_CERT, ssl_version=ssl.PROTOCOL_TLSv1_1) if not hasattr(ssl, 'PROTOCOL_TLSv1_1') or not hasattr(ssl, 'PROTOCOL_TLSv1_2'): ...
Python
1
. Please identify the disease(s) or condition(s). | Periapical radiolucency at the apex of the posterior tooth consistent with chronic apical periodontitis (periapical granuloma versus small radicular cyst) associated with a non‑endodontically treated tooth; correlate clinically and consider endodontic therapy. | This ...
Python
1
; pub use docchi_fs::common::reserved_filename; pub use docchi_fs::common::FileData; //pub use docchi_fs::common::read_archive; //pub use docchi_fs::common::load_archive; // pub mod hash{ // pub use docchi_fs::common::hash::folder_name_to_hash; // pub use docchi_fs::common::has...
Rust
0
:.6f}") print(f" 夏普比率: {result.sharpe_ratio:.6f}") print(f" 交易次数: {result.total_trades}") print(f" 胜率: {result.win_rate:.6f}") # 5. 深度分析问题 print(f"\n🔍 深度问题分析:") # 检查持仓变化 if 'pos' in df_equity.columns: pos_changes = df_equity['pos'].diff().fill...
Python
1
"""A generic archiver service.""" from jupiter.core.domain.storage_engine import DomainUnitOfWork from jupiter.core.framework.base.entity_id import EntityId from jupiter.core.framework.context import DomainContext from jupiter.core.framework.entity import ( ContainsLink, CrownEntity, RootEntity, StubEn...
Python
1
Vec::new(); // First, generate the vertices. let x_step: N = na::convert(1.0 / nx as f64); let y_step: N = na::convert(1.0 / ny as f64); for i in 0..=nx { let x = x_step * na::convert(i as f64) - na::convert(0.5); for j in 0..=ny { let y = y_ste...
Rust
0
async fn recv_403() { let server = server::http(move |req| async move { if req.uri().to_string() == "/data" && req.method() == reqwest::Method::POST { let json = json!({}); http::Response::builder() .status(hyper::StatusCode::FORBIDDEN) ...
Rust
0
if linear_full is None or linear_full.numel() != N * H * W: linear_full = torch.arange(N * H * W, device=dev, dtype=torch.int64) linear_cache[linear_key] = linear_full batch_idx = (linear_full[mask]) // (H * W) # Corner integer coords x0 = torch.floor(fltX_flat) ...
Python
1
ect a single sequence fixed_seq = to_sequence(fixed_chain, allow_hetero=True)[0][0] mobile_seq = to_sequence(mobile_chain, allow_hetero=True)[0][0] common_alph = common_alphabet([fixed_seq.alphabet, mobile_seq.alphabet]) if common_alph is None: raise ValueError("Cannot super...
Python
1
#!/usr/bin/env python3 """ Demo script to test the CRISPR Toolkit GUI with the new Single-Cell tab. """ import sys from pathlib import Path # Add src to path project_root = Path(__file__).parent src_path = project_root / "src" sys.path.insert(0, str(src_path)) def main(): """Test the GUI launch.""" print("🧬...
Python
1
TC_8x5_SRGB_BLOCK [(8, 5)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, ASTC_8x6UnormBlock => FORMAT_ASTC_8x6_UNORM_BLOCK [(8, 6)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, ASTC_8x6SrgbBlock => FORMAT_ASTC_8x6_SRGB_BLOCK [(8, 6)] [Some(16)] [compressed=texture_compression_astc_ldr...
Rust
0
west::Client::new(); // let url = format!( // "https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl={lang}&dt=t&q={text}", // lang = lang, // text = utf8_percent_encode(&text, QUERY_ENCODE_SET)); let api_key = std::env::var("GOOGLE_TRANSLATE_API_KEY") .expect("...
Rust
0
status == "danger" else "OK" print(f"[{tag}] {name}") elif cmd == "extract": dest = Path(sys.argv[3]) if len(sys.argv) > 3 else archive.with_suffix("") # default dest extract_zip_safe(archive, dest) print(f"Extracted safe ZIP entries to: {dest}") els...
Python
1
// Unless explicitly stated otherwise all files in this repository are licensed under the // MIT/Apache-2.0 License, at your convenience // // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2020 Datadog, Inc. // use std::future::Future; use std::io::{self, IoSlice, IoSliceMu...
Rust
0
ise CustomException("pretend something went wrong") with atomic_db.atomic_batch() as batch: assert batch[b"key-1"] == b"origin" assert b"key-2" not in batch def test_atomic_db_with_exception_batch(self, atomic_db: AtomicDatabaseAPI) -> None: atomic_db.set(b"key-1", b"value-...
Python
1
), _ => errors::password(e), }) } fn supports_prospective_signing(&self, address: &Address, password: &SignWith) -> bool { // If the account is permanently unlocked we can try to sign // using prospective nonce. This should speed up sending // multiple subsequent transactions in multi-threaded RPC environ...
Rust
0
binary` len: bufSize #[cfg_attr(feature = "inline", inline)] #[cfg_attr(feature = "inline_always", inline(always))] pub unsafe fn glGetProgramBinary( program: GLuint, bufSize: GLsizei, length: *mut GLsizei, binaryFormat: *mut GLenum, binary: *mut c_void, ) { #[cfg(all(debug_assertions, feature = "de...
Rust
0
nal with - this results in the final map /// in the with section /// /// # Errors /// for unknown keys pub fn ingest_creational_with(&mut self, creational: &CreationalWith<'script>) -> Result<()> { // Ingest creational `with` into definitional `args` and error if `with` contains // a...
Rust
0
be changed // in the future let mut target = glium::Frame::new(context.clone(), context.get_framebuffer_dimensions()); target.clear_color(0.0, 1.0, 0.0, 1.0); target.finish().unwrap(); // the window is still available events_loop.run_forever(|event| { match event { glutin::...
Rust
0
_eq!(source, expected); } #[test] fn write_with_shift_11_works_when_bit_shift_is_greater_than_5() { // On 5th word the bit shift is 7; on 2th it's 6. let mut source: [u8; 9] = [0; 9]; let value = 0b11111111111; let expected = [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0xFF, 0b110...
Rust
0
p & !(if is_mmio { PCI_COMMAND_MEM_EN } else { PCI_COMMAND_IO_EN }), ); // Figure out the size of this BAR region by writing 1's to the address bits let addr_mask = if is_mmio ...
Rust
0
self.buffer_links[&id] } /// Set link index for given chain. pub fn set_buffer_link(&mut self, id: Id, link: usize) { assert!(self.buffer_links.insert(id, link).is_none()); } /// Get link index for resource by id. pub fn image_link_index(&self, id: Id) -> usize { self.im...
Rust
0
try: if 'tls' in x: if x['tls'] not in [False, True]: continue x['name'] = str(flag.flag(country)) + ' ' + str(country) + ' ' + str(count) + ' ' + 'HTT' # authentication = 'userpass...
Python
1
# ****************************************************************************** # Copyright 2017-2018 Intel Corporation # # 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.apa...
Python
1
#!/usr/bin/env python """ display environment information that is frequently used to troubleshoot installations of Jupyter or IPython """ from __future__ import annotations import os import platform import subprocess import sys from typing import Any, Optional, Union def subs(cmd: Union[list[str], str]) -> Optional[...
Python
1
""" Plugin for ResolveURL Copyright (C) 2011 t0mm0 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ...
Python
1
#!/usr/bin/env python3 """ Claude Code Hook: Bash Command Validator ========================================= This hook runs as a PreToolUse hook for the Bash tool. It validates bash commands against a set of rules before execution. In this case it changes grep calls to using rg. Read more about hooks here: https://do...
Python
1
/// The cookie for the reply to a `Shape::QueryVersion` request. /// /// Pass this cookie to [`xcb_shape_query_version_reply`] to retrieve the reply. /// /// [`xcb_shape_query_version_reply`]: XcbShape::xcb_shape_query_version_reply #[derive(Copy, Clone, Debug)] #[repr(C)] pub struct xcb_shape_query_version_cookie_t {...
Rust
0
import pytest import keras.ops as K from centimators.losses import SpearmanCorrelation, CombinedLoss def _constant(array_like): # Helper to create backend tensor regardless of active backend return K.convert_to_tensor(array_like, dtype="float32") def test_spearman_correlation_loss_negative(): y_true = ...
Python
1
# SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen # SPDX-License-Identifier: BSD-3-Clause # Example to show how vtkCocoaAutoreleasePool can be used to reduce # peak RAM consumption in a VTK-Cocoa program. # Please note, the memory tracking done by this example is very crude. # The resu...
Python
1
let pages: Vec<&str> = document .find(Attr("id", "mw-pages").descendant(Name("a"))) // Get pages under <div id="mw-pages"> <a href="..."> </a> </div> .filter_map(|n| n.attr("href")) .collect(); pages.par_iter() .for_each(|x| get_page(x, append_html)); } fn get_page(rel_url: &str, ap...
Rust
0
import csv, sys args = sys.argv if len(args) != 2: print("python post_processing.py path_to_buffer_stream_folder") assert False dir_name = args[1] print (f"read file from {dir_name}") def csv2dict(dir_name, buf_name): agg_smt = {} key_list = [] with open(dir_name + buf_name + '_SMT.csv') as agg_st...
Python
1
e): add_url_rules = [['/bank', 'bank_view']] title = '收款银行' MCLS = BankTable per_page = 30 template = 'cms/bankCard/bankList.html' sort = [['statu', -1]] def get_filter_dict(self): return {'code': {'$in': BANK_CODE}} def edit_html(self): html = '' html += f''' ...
Python
1
e>vangroan/rust-wren use crate::{ bindings, types::WrenType, value::ToWren, vm::{WrenContext, WrenVm}, }; use smol_str::SmolStr; use std::{ error::Error, ffi::CString, fmt::{self, Display}, }; pub type WrenResult<T> = ::std::result::Result<T, WrenError>; #[derive(Debug)] pub enum WrenError...
Rust
0
"original_prompt", "") character_prompt = data.get("character_prompt", "") target_features = data.get("target_features", []) logger.info(f"[Debug Prompt] Received data: original_prompt='{original_prompt}', character_prompt='{character_prompt}'") settings = load_llm_settings() c...
Python
1
'n07555863', #food (24) 'n03405725', #furniture (21) 'n02469914', #primate (20) ], 'mid_12': ['n02084071', #dog (100+) 'n01503061', #bird (52) 'n04576211', #wheeled vehicle ...
Python
1
from molDistill.baselines.utils.moleculenet_encoding import mol_to_graph_data_obj_simple DESCRIPTORS = [ "usrcat", "electroshape", "usr", #"ecfp-count", "ecfp", "estate", "erg", "rdkit", "topological", "avalon", "maccs", "atompair-count", "topological-count", "f...
Python
1
*client_id % 4 { 0 => Color::rgb(1.0, 0.3, 0.3), 1 => Color::rgb(0.3, 0.8, 0.4), 2 => Color::rgb(1.0, 0.8, 0.3), 3 => Color::rgb(0.3, 0.6, 1.0), _ => unreachable!(), ...
Rust
0
c<String>, i: usize, complement_most_common: bool, default_char: char) -> String { let filtered = filter_at_index(v, i, complement_most_common, default_char); return if filtered.len() == 1 { filtered[0].clone() } else { filter_until_one_remains(&filtered, i + 1, complement_most_common, defau...
Rust
0
ring>, last_name: &Option<String>, ) -> Result<(), ServiceError> { let statement = client.prepare(UPSERT_NAME_QUERY).await?; client .query( &statement, &[ &uuid, first_name.as_ref().unwrap_or(&"".to_string()), last_name.as_ref().unwrap_or(&"".to_string()), ], ) .await?; Ok(()) } <filename...
Rust
0
n:nat() _ "]" _ "]" { DataTy::ArrayShape(Box::new(dty), n) } / "&" _ prov:provenance() _ own:ownership() _ mem:memory_kind() _ dty:dty() { DataTy::Ref(prov, own, mem, Box::new(dty)) } pub(crate) rule th_hy() -> ThreadHierchyTy = "Bloc...
Rust
0
de\xd1\xe5\xe7\ \x9d\x14'\x13\xa5\x09\xcb\xc2\xc1\xaf\x11\xd5\x074a2\ \xd2\xb5\xc0;\xad\x0b\x922\xf04\x10_m6/\x16\ )3\xad:`\x19\x12\x90\xaf\xa4\x5c!\xbe\x9bB\x5c\ V\x15'bv\x9e\x8d\xd8gV[\xea\xf92\xe9\xc1\ \x15\xe9\xdfR\xf1\xf5\xa9HD\xc9\xa0\x0a\xde\xa1\xdf\x96\ \xc0[\xcd\xbc\xfd \xe4_\x962\x7f\xfd\xb9\xaf~1\ \xd0\xec\x...
Python
1
lower() or "timeout" in str(e).lower(): self.error_counts['network'] += 1 raise NETWORK_ERROR(f"Network error: {e}") else: self.error_counts['parsing'] += 1 print(f"⚠️ Error processing product batch: {e}") # Return default resul...
Python
1
widestring::{U16CStr, U16CString}; use winapi::ctypes::c_int; use winapi::shared::minwindef::{BOOL, DWORD, FALSE, FILETIME, LPCVOID, LPVOID, LPDWORD, MAX_PATH, PULONG, TRUE, ULONG}; use winapi::shared::ntdef::{HANDLE, NTSTATUS, LONGLONG, LPCWSTR, LPWSTR, PULONGLONG}; use winapi::shared::ntstatus::{STATUS_BUFFER_OVERFL...
Rust
0
READER def get_disassociated_ids_for_net(cls, context, network_id): query = context.session.query(cls.db_model.id) query = query.filter_by( floating_network_id=network_id, router_id=None, fixed_port_id=None) return [f.id for f in query] @base.NeutronObje...
Python
1
_VTREF_TC`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum BB_LDO_VTREF_TCR { #[doc = "1.117/1.176 V"] _0, #[doc = "1.134/1.188 V"] _1, #[doc = "1.10/1.162 V"] _2, #[doc = "1.09/1.152 V"] _3, } impl BB_LDO_VTREF_TCR { #[doc = r" Value of the field as raw bits"] #[inline] ...
Rust
0
utput = [] output.append(int(scan_fields[0])) # run_status if output[0]==1: output.append(int(scan_fields[1])) # fix_status if output[1]==1: output.append(str(support.gps_date_to_timestamp(scan_fields[2]))) # utc output.append(str(scan_fields[3])) # latitu...
Python
1
for testing TESTCMD = 'import x; x.main()' def test(): run(TESTCMD) # print help def help(): import pydoc pydoc.pager(__doc__) _usage = """\ usage: pdb.py [-c command] ... pyfile [arg] ... Debug the Python program given by pyfile. Initial commands are read from .pdbrc files in your home directory and ...
Python
1
u8], pos: usize) { seg[pos..pos+val.len()].copy_from_slice(val) } #[derive(Debug)] struct PatchError { kind: PatchErrorKind, line_num: usize, } #[derive(Debug)] enum PatchErrorKind { Illegal(IllegalPatchReason), NotPatched(EvalError), } #[derive(Debug)] pub(crate) enum IllegalPatchReason { Ille...
Rust
0
aticmethod def split_into_segments(indices, last_idx): """Combine the start and end index into a NumPy array.""" indices = np.insert(indices, 0, 0) indices = np.append(indices, [last_idx]) start_end = np.array([indices[:-1], indices[1:]]) return np.transpose(start_end) ...
Python
1
mu_p = (vectors + S) / k # [n, feature_dim] sum to all vectors i = np.argmin(np.sqrt(np.sum((class_mean - mu_p) ** 2, axis=1))) selected_exemplars.append( np.array(data[i]) ) # New object to avoid passing by inference exemplar_vec...
Python
1
move_summary = [] for move in solution: clear_screen() print(f"Movimiento #{step}") from_row, from_col, to_row, to_col = move current_board = make_move(current_board, from_row, from_col, to_row, to_col) print_game_pyramid(current_board) ...
Python
1
fn from_str<S: Into<String>>(txt: S) -> Result<Self, ()> { let txt = txt.into(); if txt.starts_with("unix:") { let addr = match txt.parse::<Self>() { Ok(addr) => addr, Err(_) => return Err(()), }; Ok(Self::from(addr)) } else { ...
Rust
0
in [[i, -i] for i in range(1, l2)] for j in i]: sph_harm_one = sph_harm[l_deg**2 : (l_deg + 1) ** 2, :] sph_harm_two = sph_harm[l2**2 : (l2 + 1) ** 2, :] integral = grid.integrate(sph_harm_one[m_ord, :] * sph_harm_two[m2, :]) if l2 != l_deg...
Python
1
erbolic cosine sinhm - Matrix hyperbolic sine tanhm - Matrix hyperbolic tangent signm - Matrix sign sqrtm - Matrix square root funm - Evaluating an arbitrary matrix function expm_frechet - Frechet derivative of the matrix exponential expm_cond - Relative condition number of expm in the Frobenius no...
Python
1
ropicalWeight::new(0.2), LogWeight::new(1.7))) ); //! This example demonstrates how to define run-time resources, i.e. multiple //! resources with the same static type. Such a pattern is useful for scripting, //! but it's generally not recommended to use this to define multiple //! resources of a standard Rust type. //...
Rust
0
import pandas as pd import math def calc_elo_diff(game_result: float, home_elo: float, visiting_elo: float, home_adv: float, scoring_margin: float) -> float: # just need to make sure i really get a game result that is float (annoying) game_result = float(game_result) adj_home_elo = float(home_elo) + float(...
Python
1
e", plot_spectrogram_to_numpy(), out[-3][0]), mel_conversion_low = ("image", plot_spectrogram_to_numpy(), out_conversion[-3][0]), audio_ori = ("audio", 22050, a[0]), audio_target = ("audio", 22050, a[1]), audio_recon = ("audio", 22050, a[2...
Python
1
can this be tightened? # We've already written the metagraph to avoid a bunch of assign ops. saver.save(sess, checkpoint_fn(layers), write_meta_graph=False) def save_graph(save_path): graph = tf.get_default_graph() graph_def = graph.as_graph_def() print "graph_def byte size", graph_def.ByteSize(...
Python
1
"""empty message Revision ID: 0063_templates_process_type Revises: 0062_provider_details_history Create Date: 2017-01-10 15:39:30.909308 """ # revision identifiers, used by Alembic. revision = "0063_templates_process_type" down_revision = "0062_provider_details_history" import sqlalchemy as sa from alembic import o...
Python
1
E: Integer + Copy> From<ContiguousIntegerSet<E>> for ContiguousIntegerSetIter<E> { fn from(contiguous_integer_set: ContiguousIntegerSet<E>) -> ContiguousIntegerSetIter<E> { ContiguousIntegerSetIter { contiguous_integer_set, current: E::zero(), } } } impl<E: Integer + Cop...
Rust
0
from collections import defaultdict from chess import Board, pgn import chess from Crypto.Util.number import bytes_to_long def string_to_bits(s): binary_string = bin(bytes_to_long(s.encode()))[2:] padding_length = (8 - len(binary_string) % 8) % 8 padded_binary_string = binary_string.zfill(len(binary_string...
Python
1
rties ) user_prefs = recursive_update(user_prefs, preferences) user.preferences = user_prefs try: session.commit() except IntegrityError as e: if "duplicate key value violates unique constraint" in str(e): ...
Python
1
flatten_priors.new_full( (featmap_size[0] * featmap_size[1] * self.num_base_priors, ), stride) for featmap_size, stride in zip(featmap_sizes, self.featmap_strides) ] flatten_stride = torch.cat(mlvl_strides) # flatten cls_scores, bbox_preds and objectness flatten...
Python
1
self.object_id_to_node_id_map.get_mut(&object_id).unwrap(); node_ids.insert(node_id); node_id } pub fn nodes(&self) -> &HashMap<NodeId, SceneNode> { &self.nodes } pub fn transparent_node_ids(&self) -> &BTreeMap<Z, HashSet<NodeId>> { &self.transparent_node_ids } ...
Rust
0
""" Block ud.FixRoot will ensure that the tree is free of common root-related errors. Simple heuristics are used; it is likely that human inspection would lead to a different solution. Nevertheless, if a quick fix is needed to pass the validation, this block can be helpful. WARNING: The block currently ignores enhance...
Python
1
//! relative-schedule-spec = amount [SP] time-unit //! //! amount = 1*4DIGIT //! //! time-unit = second / minute / hour //! time-unit =/ day / week / fortnite //! time-unit =/ month / quatal //! time-unit =/ year / decade / century //! //! second = "s" ["ec" ["ond" ["s"]]] //! minute = "m" ["in" ["ute" ["s"]]] //! hour...
Rust
0
import heatflow from heatflow import Tensor a = Tensor([[[1, 2, 3, 4], [1, 2, 3, 4]], [[1, 2, 3, 4], [1, 2, 3, 4]]]) print(a.shape) print(a.flatten()) print(a.expand_dims(axis=1)) print(a.squeeze()) print("-------------------------/n") print(heatflow.flatten(a)) print(heatflow.squeeze(a)) print(heatflow.zeros(2, 2, 5...
Python
1
VERSION = "1.0.4" # fmt: off MAPPING = { "aes_pkcs5": "https://aes-pkcs5.readthedocs.io/en/latest/", "aes_pkcs5.algorithms": "https://aes-pkcs5.readthedocs.io/en/latest/overview.html", "aes_pkcs5.algorithms.aes_cbc_pkcs5_padding": "https://aes-pkcs5.readthedocs.io/en/latest/overview.html", "aes_pkcs5.a...
Python
1
} // Check that the name contains only allowed characters. if !s .chars() .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '/') { return Err(()); } // Parse into components and validate each for part in s.split...
Rust
0