text
string
label_name
string
labels
int64
write(15, (*seamless_splice & (0x7FFF << 15)) >> 15).unwrap(); afe_writer.write_bit(true).unwrap(); afe_writer.write(15, *seamless_splice & 0x7FFF).unwrap(); afe_writer.write_bit(true).unwrap(); } } } data } pub fn write_adaptation_field_extension(writer: &mut BitWriter<BigEndian>...
Rust
0
import time from functools import wraps from typing import Any, Callable def throttle(seconds: int) -> Callable[..., Any]: def decorator(func: Callable[..., Any]) -> Callable[..., Any]: last_called: float = 0 last_result: Any = None @wraps(func) def wrapped(*args: Any, **kwargs: A...
Python
1
unsafe { unsafe{ mbufs.set_len(0) }; } } if recv_pkt_num_from_outside == 0 { pull_none += 1; } else { pull_none = 0; pkt_count += recv_pkt_num_from_outside as u64; } // if pkt_count != 0 && pull_n...
Rust
0
} } #[derive(Debug, Error)] pub enum GraphError { #[error("Errors Neo4j {0:?}")] Neo4j(Vec<Neo4jError>), #[error("Statement {0}")] Statement(String), #[error("Transaction {0}")] Transaction(String), #[error("IO/Error {0}")] Io(#[from] io::Error), #[error("FromUtf8")] FromUtf8(#[from] FromUtf8Err...
Rust
0
from PyFDFD.io.EMObject import EMObject from PyFDFD.grid.Grid3d import Grid3d from PyFDFD.shape.Box import Box from PyFDFD.base.Axis import Axis from PyFDFD.base.Sign import Sign from PyFDFD.base.GT import GT import torch def assign_material_node(grid3d:Grid3d, object_array, eps_node_cell = None, mu_node_cell = None):...
Python
1
import sys input = sys.stdin.readline N = int(input()) road = [list(map(int, input().split())) for _ in range(N)] visited = [0] * N # 방문 도시 체크 def dfs(start, v, value, count): global answer visited[v] = 1 if count == N: # 모든 도시를 다 거쳐간 경우 if road[v][start] != 0: # 마지막 도시에서 시작도시로 갈 수 있다면 ...
Python
1
" | "u64" | "i8" | "i16" | "i32" | "i64" | "f32" | "f64" ) { let a: proc_macro2::TokenStream = v.parse().unwrap(); parse_quote!(arrow2::array::MutablePrimitiveArray<#a>) } else if v == "NaiveDate" { parse_quote!(arrow2::array::MutablePrimitiveArray<i32>) } else if v == "NaiveDateTime...
Rust
0
} else { Ok(activity) } } fn main() { let args: CommandArgs = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); if args.flag_help { eprintln!("{}", USAGE); return; } let is_tty = unsafe { libc::isatty(libc::STDOUT_FILENO ...
Rust
0
e api key from database, with help of uid. /// `uid` is restricted in alphabets, numbers, and `-`. pub async fn api(&self, uid: &str) -> Result<String> { if let false = uid.chars().all(is_valid_uid) { return Err(InvalidCharacterError::from(uid))?; } let tmp: [u8; 32] = crate:...
Rust
0
nt of $z$. </dl> >> Tan[0] = 0 >> Tan[Pi / 2] = ComplexInfinity #> Tan[0.5 Pi] = 1.63312*^16 """ mpmath_name = "tan" rules = { "Tan[(1/2) * Pi]": "ComplexInfinity", "Tan[0]": "0", "Derivative[1][Tan]": "Sec[#]^2&", } class Tanh(_MPMathFunction...
Python
1
;<reponame>Byron/git-rs #![deny(unsafe_code, rust_2018_idioms, missing_docs)] //! A shared trust model for `gitoxide` crates. use std::{ fmt::{Debug, Display, Formatter}, marker::PhantomData, ops::Deref, }; /// A way to specify how 'safe' we feel about a resource, typically about a git repository. #[deriv...
Rust
0
# Exercício solucionado: calculando as datas e parcelas de um empréstimo # Maria pegou um empréstimo de 1.000.000 # para realizar o pagamento em 5 anos. # A data em que ela pegou o empréstimo foi # 20/12/2020 e o vencimento de cada parcela # é no dia 20 de cada mês. # - Crie a data do empréstimo # - Crie a data do fina...
Python
1
Nothing /// /// In all cases, whitespace after the prefix is cleared. #[allow(clippy::needless_lifetimes)] // Clippy and the compiler disagree pub async fn prefix<'a>( ctx: &Context, msg: &Message, stream: &mut Stream<'a>, config: &Configuration, ) -> Option<Cow<'a, str>> { if let Some(id) = mentio...
Rust
0
from app.objects.secondclass.c_fact import Fact from app.objects.secondclass.c_relationship import Relationship from app.utility.base_parser import BaseParser from ipaddress import ip_address, ip_interface class Parser(BaseParser): """ Functionality that parses network and IP addresses and stores the pairs a...
Python
1
"{:.2f}".format(results["plan_obj_box_col_1s"]*100), "{:.2f}".format(results["plan_obj_box_col_2s"]*100), "{:.2f}".format(results["plan_obj_box_col_3s"]*100), \ "{:.2f}".format(((results["plan_obj_box_col_1s"] + results["plan_obj_box_col_2s"] + results["plan_obj_box_col_3s"])/3...
Python
1
callback_query(call.id, "Already running!") elif call.data == "stop_check": running = False paused = False bot.answer_callback_query(call.id, "Stopped checking credit cards!") elif call.data == "hold_check": if running: paused = True running = False ...
Python
1
clone(), false => paint.get_fill_path(path, None, None).unwrap() }; path_1d_path_effect::new( &marker, self.state.line_dash_list[0], self.state.line_dash_offset, self.state.line_dash_fit ) } None => dash_path_effec...
Rust
0
# Purpose: This script hides the 'Roofs' category in the active Revit 3D view. # Import necessary classes import clr clr.AddReference('RevitAPI') from Autodesk.Revit.DB import ( View3D, BuiltInCategory, Category, ElementId, View # Base class for type checking ) import System # For Exception handli...
Python
1
} } } pub struct Proposal { is_conf_change: bool, index: u64, term: u64, pub cb: Callback, } impl Proposal { pub fn new(is_conf_change: bool, index: u64, term: u64, cb: Callback) -> Proposal { Proposal { is_conf_change, index, term, cb, ...
Rust
0
s allowed by the ACL rules. pub fn is_allowed(&self, server_name: &ServerName) -> bool { if !self.allow_ip_literals && server_name.is_ip_literal() { return false; } let host = server_name.host(); self.deny.iter().all(|d| !WildMatch::new(d).matches(host)) && ...
Rust
0
lap; let x1 = input.x1 - half_overlap; Rect::new(x0, input.y0, x1, input.y1) } } use std::process; use anyhow::Result; use colored::Colorize; use dialoguer::{theme::ColorfulTheme, Confirm}; use structopt::StructOpt; use crate::utils::{config::Config, profile::Profile, profiles::Profiles}; #[deriv...
Rust
0
ecting!"); // We need to kill the Actor responsible for Commit monitoring, too // act.lobby_addr.do_send(Disconnect { id: act.id, room_id: act.room }); // stop actor ctx.stop(); // don't try to send a ping return; ...
Rust
0
&Element) -> c_int { unsafe { _element_cmp(self._ptr, rhs._ptr) } } // Random pub fn random(&mut self) { unsafe { _element_random(self._ptr); } } // Hashing pub fn set_from_hash(&mut self, h: Vec<u8>) { unsafe { _element_from_hash(self...
Rust
0
0, 0,0,0, 252,252,252, 164,228,252, 184,184,248, 216,184,248, 248,184,248, 248,164,192, 240,208,176, 252,224,168, 248,216,120, 216,248,120, 184,248,184, 184,248,216, 0,252,252, 248,216,248, 0,0,0, 0,0,0]; pub const SPRITE_WIDTH: usize = 8; pub const S...
Rust
0
dd_window_by_handle(handle, properties) } pub fn remove_wallpaper(&self, hwnd: HWND) { // TODO ensure that provided handle is actually attached to wallpaper window use winapi::um::winuser::{InvalidateRect, SendMessageW, WM_CLOSE}; unsafe { remove_window_from_wallpaper(self....
Rust
0
extensão permitida ou é um Dockerfile (que pode não ter extensão) if file_extension not in allowed_extensions and not file_name.endswith('Dockerfile'): continue # Atualizar a barra de progresso com a porcentagem correta file_count += 1 ...
Python
1
t, total = await services.athena_query_repo.list( session, offset, page_size ) # Calculate pagination metadata total_pages = (total + page_size - 1) // page_size next_page = page + 1 if page < total_pages else None prev_page = page - 1 if page > 1 else None ...
Python
1
class Gato: def __init__(self, nombre, edad): self.nombre = nombre # Atributo público self.__edad = edad # Atributo privado (encapsulado) self.dueño = None # Referencia al dueño del gato def asignar_dueño(self, dueño): self.dueño = dueño def mostrar_info...
Python
1
# Copy items in sorted order dct = OrderedDict() dct["browser_id"] = browser_id for key in sorted(item.keys()): dct[key] = item[key] table_input.append(dct) key_dict = OrderedDict() counter = 0 for key in table_input[0].keys(): key_dict[key] = counter ...
Python
1
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: LicenseRef-NvidiaProprietary # # NVIDIA CORPORATION, its affiliates and licensors retain all intellectual # property and proprietary rights in and to this material, related # documentation and a...
Python
1
import csv import os import sys import re def extract_tracking_id(text): """件名からTrackingIDを抽出する関数""" # TrackingID#に続く数字を検索するパターン pattern = r"TrackingID#(\d+)" match = re.search(pattern, text) if match: return match.group(1) # 数字部分だけを返す return None def match_rate(str1, str2): # まずT...
Python
1
array(data) # x is shorthand from earlier code if transform == 'abs': tfunc = np.abs elif transform == 'square': tfunc = lambda x: x * x # noqa elif transform == 'identity': tfunc = lambda x: x # noqa elif callable(transform): tfunc = transform else: raise...
Python
1
atabase. These mentioned elements are included in [`common`], [`date`] and [`error`] modules. //! //! [`ApiKey`](struct@crate::<EMAIL>::ApiKey), which is a structure in [`common`], gives validity to all functions //! playing role to make requests for EVDS web services. Therefore, users need to utilize their keys to wor...
Rust
0
link.callback(|name| Msg::SelectCity(name)); html! { <> <MapComponent city=&self.city /> <Control select_city=cb cities=&self.cities/> </> } } } fn main() { yew::initialize(); let document = yew::utils::document(); let app = docum...
Rust
0
num = int(input("Enter a number: ")) print("Square:", num ** 2)
Python
1
4IV_72 = 72, #[doc = "74: Interrupt Source: ADC14MEM31 interrupt flag; Interrupt Flag: ADC14IFG31"] ADC14IV_74 = 74, #[doc = "76: Interrupt Source: ADC14RDYIFG interrupt flag; Interrupt Flag: ADC14RDYIFG; Interrupt Priority: Lowest"] ADC14IV_76 = 76, } impl From<ADC14IV_A> for u32 { #[inline(always)...
Rust
0
()]); let res_v = self.to_val(res.clone(), next)?; let to_v = self.to_val(to(&res_v), next)?; self.add_stmt( next, PrimStmt::AsgnVar( Ident::unused(), PrimExpr::CallBuiltin(Function::S...
Rust
0
import cv2 import numpy as np import csv from skimage.measure import label, regionprops i = 1 # Load your frame (replace 'ExpFrames/frame{}.jpg' with the actual file path) image = cv2.imread('ExpFrames/frame{}.jpg'.format(i), 0) # Threshold the image to create a binary mask ret, binary_mask = cv2.threshold(image, 110...
Python
1
: ::std::os::raw::c_int); } extern "C" { pub fn SetMouseOffset(offsetX: ::std::os::raw::c_int, offsetY: ::std::os::raw::c_int); } extern "C" { pub fn SetMouseScale(scaleX: f32, scaleY: f32); } extern "C" { pub fn GetMouseWheelMove() -> f32; } extern "C" { pub fn SetMouseCursor(cursor: ::std::os::raw::c_...
Rust
0
_photo_uz') change_bio = types.InlineKeyboardButton('Tarzimai holni o\'zgartirish 📋', callback_data='change_bio_uz') markup.add(change_photo, change_bio) else: add_cv = types.InlineKeyboardButton('Rezyume yaratish 🪪', callback_data='add_cv_uz') markup.add(add_cv) change_phone_...
Python
1
self.weights.len() } pub fn bias(&self) -> Num { self._bias } pub fn clone_weights(&self) -> Vec<Num> { self.weights.clone() } pub fn feedforward(&mut self, inputs: &[Num]) { let summed_weights: Num = self .weights .iter() .zip(input...
Rust
0
We will decode one // block twice, once into each buffer. If both decodes are successful, then // the two outputs should be identical. If we don't overwrite parts of the // buffer, then we would see a difference in the marker byte. The buffer // allocated up front should be large enough that Claxon doe...
Rust
0
.await; self.irrecoverable_signal = tr_irrecoverable; self.cancellation_signal = Some(tx_cancellation); self.join_handle = Some(wrapped_handle); self.run().await } /// Run watches continuously for irrecoverable errors or JoinHandle completion. async fn run(mut self) -> R...
Rust
0
rred is too low to create a vesting schedule. AmountLow, /// An index was out of bounds of the vesting schedules. ScheduleIndexOutOfBounds, /// Failed to create a new schedule because some parameter was invalid. InvalidScheduleParams, } #[pallet::call] impl<T: Config> Pallet<T> { /// Unlock any vested f...
Rust
0
!( context, responder, SettingType::Intl, settings.into(), Ok(()), Err(fidl_fuchsia_settings::Error::Failed), IntlMarker ); }) .detach(); ...
Rust
0
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import beanmachine.ppl as bm import pytest import torch import torch.distributions as dist from beanmachine.ppl.inference.proposer.hmc_propo...
Python
1
ssage<M> for GetSingularMessageImpl<M, N> { fn get_message<'a>(&self, m: &'a M) -> &'a Message { (self.get)(m) } } trait GetSingularEnum<M> { fn get_enum(&self, m: &M) -> &'static EnumValueDescriptor; } struct GetSingularEnumImpl<M, E> { get: fn(&M) -> E, } impl<M: Message, E: ProtobufEnum> G...
Rust
0
#!/usr/bin/env python import math from settings import * total_avaliable_pfs = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048] def get_conv_pfs(target_pf, channel_num, kernel_num): # set to the closest avaliable pfs actual_pf = min(MAX_CPF * MAX_KPF, 2 ** int(round(math.log(float(target_pf)) / math.log(2...
Python
1
; // Registers addresses pub const INTERRUPT_ENABLE: Address = 0xFFFF; /// LCD Control register addres pub const LCDC: Address = 0xFF40; /// LCD Status register address pub const LCDS: Address = 0xFF41; /// Scroll position Y pub const SCY: Address = 0xFF42; /// Scroll position X pub const SCX: Address = 0xFF43; /...
Rust
0
surface_normal.cross(dvec3!(0.0, 1.0, 0.0).cross(surface_normal)); Some(Intersect::new(ray, dist, hit_point, surface_normal, surface_tangent, surface_coord)) } } } impl Intersectable for Sphere { fn get_closest_intersect(&self, ray: Ray) -> Option<Intersect> { let intersects = self...
Rust
0
>`, /// where type can be `tcp`, `unix` or `pipe`. /// If `<SCHEME>` is omitted, `tcp` is assumed. /// `<ADDRESS>` should be specified as `<HOST>:<PORT>` for `tcp`, /// as a valid file path for `unix` and as a valid pipe name for `pipe`. /// /// Example: `[::]:80->localhost:8080` /// {n}Exam...
Rust
0
the spatial tree to search for users near ours in user-feature-space. // We request one more because the search will also return our anime itself let similar_users = state.user_feature_tree.nearest(&user_point, k + 1, &|u0, u1| { u0.iter().zip(u1).map(|(u0v, u1v)| (u0v - u1v).po...
Rust
0
y determine the maximum charge state of the precursor to consider.", disabled=st.session_state["sidebar_disabled"]) if not max_charge_auto: st.number_input("Max Charge:", key="max_charge", ...
Python
1
); vec![] } } } fn create_page(input: PathBuf, defaults: &Object, renderers: &Renderers) -> Option<Page> { debug!( "loading {:?}", input.as_path().file_name().unwrap_or_default() ); let input_str = fs::read_to_string(&input).unwrap_or_else(|err| { debug!("Unable to read {:?}! {}", &input, err); Strin...
Rust
0
ass - simple regular expression pass to see if the resulting domains /// are indeed valid domains. pub fn filter_domains<T>(permutations: T) -> impl Iterator<Item = String> where T: Iterator<Item = String>, { permutations .filter(|x| is_valid_punycode(x) && IDNA_FILTER_REGEX....
Rust
0
crash!(1, "cannot chroot to {}: {}", root_str, Error::last_os_error()) }; } fn set_main_group(group: &str) { if !group.is_empty() { let group_id = match get_group(group) { None => crash!(1, "no such group: {}", group), Some(g) => g.gr_gid }; let err = unsaf...
Rust
0
elf, other: &[u8]) { assert_eq!(other, self) } } /// Tests whether the file can be successfully loaded /// and produces the expected output during it pub(crate) fn load_module_test<T: Expectable>(file: &str, expected: T) { use scryer_prolog::*; let input = machine::Stream::from(""); let output...
Rust
0
el.add(BatchNormalization(input_shape=(trainData.shape[1], trainData.shape[2], 1))) model.add(layers.Conv2D(16, (2, 2),strides=2, activation='relu', input_shape=(trainData.shape[1], trainData.shape[2], 1))) model.add(BatchNormalization())# model.add(layers.MaxPooling2D((2, 2)))#1 model.add(layers.Conv2D(32, (3, 3),str...
Python
1
def contains(bag, e): # 가방안에 찾는 물건이 있는지 알려주는 함수 return e in bag def insert(aaa, p): aaa.append(p) def remove(bbb, p): bbb.remove(p) def count(bag): # 가방안에 갯수를 count해주는 함수 return len(bag)+5 myBag = [] insert(myBag, '휴대폰') # => 결과 : ['휴대폰'] insert(myBag, '지갑') # => ['휴대폰', '지갑'] insert...
Python
1
for _column in parsed_sql[type]: if isinstance(_column['value'], int): continue elif isinstance(_column['value'], str): index = 0 if _column['value'] in columns: index = columns.index(_column['value']) + 1 ...
Python
1
ие индекса удобочитаемости LIX Описание: Чем выше показатель, тем сложнее текст для чтения Значения индекса лежат в пределах от 0 до 100 и могут интерпретироваться следующим образом: 0-30 - Очень простые тексты, детская литература 30-40 - Простые тексты, художественная литер...
Python
1
Expression::False )), Expression::Ternary { cond: Box::new(Expression::True), then: Box::new(Expression::SelfExpr), else_: Box::new(Expression::Nil), } )] ); */ assert_eq!( lex_parse!("a ? b : c ? d : e"...
Rust
0
t OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }; INTTCSTAT6R { bits } } #[doc = "Bit 7 - Terminal count interrupt request status for DMA channels. Each bit represents one channel: 0 - the corresponding channel has no active terminal count interrupt request. 1 - the cor...
Rust
0
import numpy as np # type: ignore from src.scene import ( Materials, BoxDimensions, SceneConfig, RectPrism, CubeParams, Subdivisions, ) # ---- Room dimensions ---- W, D, H = 5.0, 5.0, 3.0 # ---- Materials ---- materials = Materials( rho_floor=0.3, rho_ceiling=0.0, rho_walls=0.0, ...
Python
1
# coding: utf-8 # Copyright (c) 2016, 2025, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
Python
1
if let UIPointType::Point((a, b)) = kind { if viewport.handle_style != HandleStyle::None { draw_handle(v, viewport, a, selected, canvas); draw_handle(v, viewport, b, selected, canvas); } } } fn draw_handle(v: &Editor, viewport: &Viewport, h: Handle, selected: bool, can...
Rust
0
unt_ones(); } n_1s as f64 / n_digits as f64 } fn khash(seed: u32) -> u32 { let n1 = 0xB5297A4D; let n2 = 0x68E31DA4; let n3 = 0x1B56C4E9; let mut mangled = seed; mangled = mangled.wrapping_mul(n1); mangled ^= mangled.rotate_right(13); mangled = mangled.wrapping_add(n2); mangle...
Rust
0
# Python Object Oriented Programming by Joe Marini course example # Using class-level and static methods class Book: # TODO: Properties defined at the class level are shared by all instances BOOK_TYPES = ("HARDCOVER", "PAPERBACK", "EBOOK") # TODO: double-underscore properties are hidden from other classes...
Python
1
padded_data.append(torch.cat((data, padding), dim=-1)) return torch.stack(padded_data) def generate_attention_mask(input_data): mask = (input_data != -0.0).any(dim=-1) # Find non-padding positions mask = mask.to(torch.float32) mask = mask.masked_fill(mask == 0, float('-inf')).masked_fill(mask ...
Python
1
put) geom.set_calculator(calc) assert geom.energy == pytest.approx(-76.418221) # Remove control_path kill_dir(calc.control_path) @using("turbomole") @pytest.mark.parametrize("mem", (100, 300, 1000)) def test_mem(mem): geom = geom_loader("lib:h2o.xyz") simple_input = { "basis": "def2-S...
Python
1
c<u8>, pub(crate) handshake_send_sequence: isize, pub(crate) handshake_recv_sequence: isize, pub(crate) server_name: String, pub(crate) remote_requested_certificate: bool, // Did we get a CertificateRequest pub(crate) local_certificates_verify: Vec<u8>, // cache CertificateVerify pub(crate) loca...
Rust
0
#!/usr/bin/python3 multiple_returns = __import__('8-multiple_returns').multiple_returns sentence = "" length, first = multiple_returns(sentence) print("Length: {:d} - First character: {}".format(length, first))
Python
1
# %% import numpy as np with open("input.txt") as f: data = f.read().splitlines() for i in range(len(data)): data[i] = np.array([int(x) for x in data[i].split(" ")]) # %% def is_safe(reports): d = reports[:-1] - reports[1:] d_abs = np.abs(d) if all(d_abs>=1) and all(d_abs<=3) and (all(d>0) or all(d...
Python
1
# Solution file from fractions import Fraction from functools import reduce def product(fracs): t =reduce(lambda x, y: x * y, fracs) return t.numerator, t.denominator if __name__ == '__main__': fracs = [] for _ in range(int(input())): fracs.append(Fraction(*map(int, input().split()))) res...
Python
1
"pchain": "07bcf65f187117b4:5020393" }, "tmax": 1499, "user": { "ext": { } } }"#; pub const OUTSTREAM: &str = r#"{ "allimps": 0, "app": { "bundle": "defaultBundleId", "cat": [ "IAB7-42" ], "id": "294", "name": "appNa...
Rust
0
await?; buf.resize(len, 0); buf_reader.read_exact(&mut buf).await?; socket_cloned.send(&buf.copy_to_bytes(len)).await?; } { log::info!( ...
Rust
0
, ForEach, ForEachKey, MiniscriptKey, Satisfier, ToPublicKey, TranslatePk, TranslatePk2, }; mod bare; mod blinded; mod covenants; mod segwitv0; mod sh; mod sortedmulti; // Descriptor Exports pub use self::bare::{Bare, Pkh}; pub use self::blinded::Blinded; pub use self::segwitv0::{Wpkh, Wsh, WshInner}; pub use self...
Rust
0
import torch import torch.nn as nn from scipy.ndimage import gaussian_filter1d import numpy as np def np2tensor(v): return torch.from_numpy(v).type(torch.float) def np2param(v, grad=True): return nn.Parameter(np2tensor(v), requires_grad=grad) def get_device(): is_cuda = torch.cuda.is_available() if ...
Python
1
# Copyright 2025 Snowflake Inc. # SPDX-License-Identifier: Apache-2.0 # 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 applicabl...
Python
1
/]+)/genid/(?P<genId>[^/]+)/decrypt$") .expect("hard-coded regex must compile"); let captures = uri_regex.captures(path)?; let module_id = &captures["moduleId"]; let module_id = percent_encoding::percent_decode_str(module_id) .decode_utf8() .ok()?; ...
Rust
0
heck_move(&vt, &move1), true); /// /// let move2 = CartessianND{coord : vec![1, 1, 0]}; /// assert_eq!(sys.check_move(&vt, &move2), false); /// ``` /// /// # Panic /// /// point와 movement가 서로 차원이 다르면 compile error가 생기거나 panic이 일어납니다. /// ```should_panic /// # use moldybrody::syst...
Rust
0
); } } } pub fn get_terminal_size() -> (u16, u16) { unsafe { debug!("Getting terminal size"); let mut term_size = c::bis_term_size_t { rows: 0, cols: 0 }; if c::bis_get_terminal_size(&mut term_size) != 0 { c::c_panic(); } (term_size.rows, term_size....
Rust
0
end(read(&mut stream)); if ret[ret.len() - 1] == b'\n' { poll.registry() .reregister(&mut stream, token, Interest::WRITABLE) .unwrap(); break 'end_ackjob; } else { poll.registry() ...
Rust
0
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. import atexit import contextlib import sys from .ansitowin32 import AnsiToWin32 def _wipe_internal_state_for_tests(): global orig_stdout, orig_stderr orig_stdout = None orig_stderr = None global wrapped_stdout, wrapped_stderr...
Python
1
e()); let _data = transmute::<*c_void, ~RequestData>(data); uvll::set_data_for_req(self.native_handle(), null::<()>()); uvll::free_req(self.native_handle()); } } } impl NativeHandle<*uvll::uv_getaddrinfo_t> for GetAddrInfoRequest { fn from_native_handle(handle: *uvll...
Rust
0
ddrKnown::new(DEFAULT_MAX_KNOWN) } } #[derive(Clone, Debug, PartialOrd, Ord, Eq, PartialEq, Hash)] pub struct ConnectableAddr { host: Bytes, port: u16, } impl From<&Multiaddr> for ConnectableAddr { fn from(addr: &Multiaddr) -> ConnectableAddr { use tentacle::multiaddr::Protocol::{DNS4, DNS6, I...
Rust
0
::glutin::{ ElementState, Event, KeyboardInput, VirtualKeyCode, WindowBuilder, WindowEvent, }; use fb_now::FbNow; use rodio::default_output_device; use rodio::source::SineWave; use rodio::source::Source; use rodio::Sink; use std::env; use std::thread; use std::time::Duration; macro_rules! keyboard_update { ($e...
Rust
0
author_counts[author] = author_counts.get(author, 0) + 1 # Sort by frequency top_categories = sorted(category_counts.items(), key=lambda x: x[1], reverse=True)[:10] top_authors = sorted(author_counts.items(), key=lambda x: x[1], reverse=True)[:10] # Log trends ...
Python
1
fn get_number_of_edges() -> usize { 6 } /// Slicing a tetrahedron with a plane will produce either 0, 3, or 4 /// points of intersection. In the case that the slicing procedure returns /// 4 unique vertices, we need to know how to connect these vertices to /// form a closed polygon (i.e. a ...
Rust
0
from .user import UserCreate, UserSignIn from .point import PointCreate
Python
1
p = int(time.time()) filename = f"output/{timestamp}.html" os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, "w", encoding="utf-8") as f: f.write(f"""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=de...
Python
1
the License for the specific language governing permissions and // limitations under the License. //! Timer configuration for ST STM32F7. //! //! This code supports only TIM2 at the moment. use super::peripheral_clock; use hal::timer; #[path="../../util/ioreg.rs"] #[macro_use] mod ioreg; /// Available timer periph...
Rust
0
import re s = input() x = re.sub(r'(?:^|_)([a-z])', lambda match: match.group(1).upper(), s) print(x)
Python
1
parse<'a>(css: &'a str) -> SyntaxNode { let parser = parser::Parser::new(css); parser.parse() } fn tokenize_bench(c: &mut Criterion) { c.bench_function("parser/small(7K)", |b| { b.iter_with_large_drop(|| parse(SMALL_CSS_FILE)); }); c.bench_function("parser/large(201K)", |b| { b.iter_with_large_drop(...
Rust
0
1, JsValue::NULL); let sort_err = toposort(&g).unwrap_err(); let expect_err = GraphError::new("Cycle detected", GraphItemType::Node, 1); assert_eq!(sort_err.into_serde::<GraphError>().unwrap(), expect_err); } <reponame>lebensterben/html5gum<gh_stars>0 macro_rules! impl_error { ($( $string:litera...
Rust
0
数据验证失败: {validation_result['message']}" } # 编译报告数据 report_data = self._compile_report_data(analysis_data, options) # 生成不同格式的报告 output_files = [] report_files = [] download_links = [] ...
Python
1
ub const DISPID_RDPSRAPI_PROP_STREAMBUFFER_CONTEXT: u32 = 560u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_STREAMBUFFER_FLAGS: u32 = 561u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_STREAMBUFFER_PAYLOADOFFSET...
Rust
0
n) for x in os.listdir(dn): if os.path.isdir(x): for y in os.listdir(x): if os.path.isfile(y): transpile_subfile(y) # go one level deeper for file in os.listdir(directory): newsubobj = directory + os.sep + file if os.path.isdir(newsub...
Python
1
# Copyright 2020-present, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Davide Abati, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch.nn as nn from torch.optim import SGD import torch impor...
Python
1
.execute(&mut *tx) .await?; } if !new_to_add.is_empty() { let info = sqlx::query!( r##" SELECT payload_schema FROM inputs WHERE input_id=$1 "##, input_id.0 ) ...
Rust
0