text
string
label_name
string
labels
int64
(i, window) in s.windows(substr.len()).enumerate() { if window == substr { return Some(i); } } return None; } // Count occurrence of ```substr``` in ```s```. fn count_substr<T: Eq>(s: &[T], substr: &[T]) -> usize { assert!(substr.len() > 0); let mut cnt = 0; for windo...
Rust
0
import io import cairosvg import PyPDF2 def generate_pdf_from_svgs(svg_list): """Generates a multi-page PDF document from a list of SVG strings. This function converts each SVG string in the provided list to a PDF page using CairoSVG. These pages are then combined into a single PDF document using PyPDF2...
Python
1
RECIPES = [ { "inputs": ["kettle (empty)", "sink"], "output": ["kettle (cold water)"], "description": "Fill kettle with cold water", }, { "inputs": ["kettle (cold water)", "stove"], "output": ["kettle (hot water)"], "description": "Boil the kettle on the stove...
Python
1
# SPDX-License-Identifier: BSD-3-Clause # Copyright 2020-2022, Intel Corporation from collections import namedtuple import testframework as t TC = namedtuple('TC', ['dest', 'src', 'length']) class PmemMemcpy(t.Test): test_type = t.Short filesize = 4 * t.MiB envs0 = () envs1 = () test_cases = (...
Python
1
"""Incident-related domain events.""" from dataclasses import dataclass from uuid import UUID from app.domain.entities import IncidentSeverity from app.events.base import DomainEvent @dataclass(frozen=True) class IncidentCreated(DomainEvent): """Event fired when a new incident is created.""" incident_id: U...
Python
1
платеже без текста, " "обработчик суммы пополнения завершает работу" ) await state.clear() return await message.answer( texts.INVALID_AMOUNT, reply_markup=get_back_keyboard(db_user.language) ) ...
Python
1
required=False, type=int, default=None, dest='lig2resid', help='Residue id of the second ligand') parser.add_argument('--LIG2refatoms', required=False, type=str, default=None, dest='lig2refatoms', help='string of reference atoms of the first ligand "1 2 3"') pa...
Python
1
# # Copyright (C) 2018 The Android Open Source Project # # 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 applicable la...
Python
1
SubCommand::with_name("print_evm_address") .setting(AppSettings::Hidden) .about("Print EVM address") .arg(Arg::with_name("secret_key") .takes_value(true) .value_name("SEC...
Rust
0
None } } } pub mod env { use libc; use std::{ env, ffi::{CStr, OsString}, mem, os::unix::ffi::OsStringExt, path::PathBuf, ptr, }; pub fn home_dir() -> Option<PathBuf> { return env::var_os("HOME") .or_else(|| unsafe { fa...
Rust
0
().collect(); if constants.is_empty() { return; } env.analysis.constants = constants::analyze(env, &constants, obj); } fn analyze(env: &mut Env, tid: TypeId, deps: &[TypeId]) { let full_name = tid.full_name(&env.library); let obj = match env.config.objects.get(&*full_name) { Some(o...
Rust
0
t = 0x49C, // SmsgOnCancelExpectedRideVehicleAura = 0x49D, // SmsgCriteriaDeleted = 0x49E, // SmsgAchievementDeleted = 0x49F, // CmsgServerInfoQuery = 0x4A0, // SmsgServerInfoResponse = 0x4A1, // CmsgCheckLoginCriteria = 0x4A2, // SmsgServerBuckDataStart = 0x4A3, // CmsgSetBreath = 0x4A4...
Rust
0
Layer for Github { type File = GithubBlob; type Directory = GithubTree; // Replace with existential type once https://github.com/rust-lang/rfcs/pull/2515 lands. #[allow(clippy::type_complexity)] type GetFuture = Pin<Box<dyn Future<Output=Result<CacheObject<Self::File, Self::Directory>, CacheError>>+...
Rust
0
import os import pytest @pytest.fixture(scope="module") def install(): pytest.helpers.clean_env() # Create a custom config pytest.helpers.custom_config() args = [ "/custom-config=custom_conf", "/master=cli_master", "/minion-name=cli_minion", ] pytest.helpers.install_sa...
Python
1
/// Pubkey returns the public key that corresponds to the given private key. pub fn pubkey(&self) -> VrfPubKey { unsafe { let mut pubkey = VrfPubKey([0; VRF_PUBKEY_BYTE_LENGTH]); ffi::crypto_vrf_sk_to_pk(pubkey.0.as_mut_ptr(), self.0.as_ptr()); return pubkey; ...
Rust
0
name.clone(), kind: original.kind, max_increase: original.max_increase, curr_increase: original.curr_increase, ..nothing.clone() }) }, } } } fn patch_add_item<'r>( ps: &mut PatcherState, area...
Rust
0
().unwrap()) }) } fn get_bitcount(bits: &Vec<Vec<u32>>) -> Vec<Bitcount> { let mut count = Vec::<Bitcount>::new(); for (i, n) in bits.iter().enumerate() { for (j, bit) in n.iter().enumerate() { if i == 0 { count.push(Bitcount::new()); } match...
Rust
0
from models import generator_unet_upsampling import h5py img_dim = (256,256,3) bn_mode = 2 batch_size = 1 model_name = "generator_unet_upsampling" import cv2 import sys import numpy as np def fDataSet_generator(img_dim_tuple,batch_size=10, f=None, indexes=1448): if(f==None): path = "../../data/nyu_depth_v2_l...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license (see the COPYING file). """ Remove a group from the current worktree """ from __future__ import absolute_import from __future__ import unicode_lite...
Python
1
_mut() { let c_code_buf: *const c_char = c_reasult.code; let c_code_str: &CStr = unsafe { CStr::from_ptr(c_code_buf) }; let code_str_slice: &str = c_code_str.to_str().unwrap(); code = Option::from(code_str_slice.to_owned()); } let mut message: Option<Stri...
Rust
0
import plotly.express as px import pandas as pd from plotly.offline import plot data = { 'Date': pd.date_range(start='2024-01-01', periods=5, freq='D'), 'Studying_Hours': [4, 3, 2, 5, 1], 'Sleep_Hours': [7, 6, 7, 8, 7] } df = pd.DataFrame(data) fig = px.line(df, x='Date', y=['Studying_Hours', 'Sleep_Hour...
Python
1
''' N, M = map(int, input().split()) A = [list(map(int, input().split())) for i in range(N)] exist = [0]*(M + 1) # 0-Mまでのバケットを作成 for a in A: for i, n in enumerate(a): # 文字列aに対してインデックスと要素を同時に取り出す if i == 0: # 入力のkはスキップ continue exist[n] +=1 # 一致するバケットの要素にインクリメント an...
Python
1
.intel.com/en-us/blogs/2011/04/14/is-avx-enabled/ let xcr_feature_mask = if (features[2] & (1 << 27)) != 0 && (features[2] & (1 << 28)) != 0 { unsafe { _xgetbv(0) } } else { 0 }; if (xcr_feature_mask & 0x6) ...
Rust
0
hich may unblock callers of join(). """ self._is_shutdown = True if immediate: while not self.empty(): self._get() if self._unfinished_tasks > 0: self._unfinished_tasks -= 1 if self._unfinished_tasks == 0: ...
Python
1
T_PIPELINE_TYPE", pipeline_import_template) \ .replace("PIPELINE_LOADING", pipeline_loading_template) \ .replace("TOKENIZER_TYPE", self.tokenizer_class_name) \ .replace("MODEL_TYPE", self.model_loader_class_name) \ .replace("TOKENIZER_PATH", f"/.azml_model_cache/{self.mod...
Python
1
# Copyright (C) 2018, 2019, 2020 Dominic O'Kane import numpy as np from financepy.market.curves.discount_curve_zeros import DiscountCurveZeros from financepy.market.curves.interpolator import InterpTypes from financepy.utils.date import Date from financepy.utils.frequency import FrequencyTypes from financepy.utils.da...
Python
1
Result<(), Box<dyn std::error::Error>> { /// let mut table = SymbolTable::with_capacity(10); /// table.intern(b"abc".to_vec()); /// table.intern(b"xyz".to_vec()); /// table.intern(b"123".to_vec()); /// table.shrink_to_fit(); /// assert!(table.capacity() >= 3); /// # Ok(()) /// # } /...
Rust
0
x, y): for i in range(0, len(coord_list), 2): coord_list[i] = coord_list[i] + x coord_list[i + 1] = coord_list[i + 1] + y return coord_list def move_to(object, x, y=None, d_o_e=None, d_w=tkinter._tkinter.DONT_WAIT): if d_o_e is None: d_o_e = _root_window.doonee...
Python
1
:new(enc_query.clone(), 1).is_ok()); assert!(Query::new(enc_query, 2).is_ok()); } } use std::collections::{VecDeque}; use std::rc::{Rc}; use std::cell::{RefCell}; use template::{EventHook}; /// Data for interacting with an active UI component tree inserted through a template. #[derive(Clone)] pub struct E...
Rust
0
0.325, 3) @testing.skipif(not has_qt, reason="Qt not installed") def test_plot_plugin(): viewer = ImageViewer(data.moon()) plugin = PlotPlugin(image_filter=lambda x: x) viewer += plugin assert_equal(viewer.image, data.moon()) plugin._update_original_image(data.coins()) assert_equal(viewer.im...
Python
1
/// .filter(|line| !line.starts_with("-")) /// .fold(String::new(), |mut data, line| { /// data.push_str(&line); /// data /// }); /// let der_bytes = base64::decode(&der_encoded).expect("failed to decode base64 content"); /// let private_key = RSAPrivateKey::from...
Rust
0
transfer...") killing_job = True file_transfer_back = False if killing_job: future_scancel = gcx.submit_to_registered_function( function_id=function_id_scancel, args=(args,)) fu...
Python
1
import pytest from vllm import SamplingParams from .conftest import get_output_from_llm_generator @pytest.mark.parametrize("common_llm_kwargs", [{ "model": "meta-llama/Llama-2-7b-chat-hf", "speculative_model": "JackFram/llama-68m", "num_speculative_tokens": 5, }]) @pytest.mark.parametrize( "per_test...
Python
1
server name, config in _settings.json #[structopt(short, long, default_value = "")] pub server: String, /// test server address, config in _settings.json #[structopt(long, default_value = "")] pub server_url: String, /// api url #[structopt(short, long, default_value = "")] pub url: S...
Rust
0
""" ) return @app.cell def _(jnp, nu, nx): Q_mat = 2*jnp.eye(nx) R_mat = jnp.eye(nu) return Q_mat, R_mat @app.cell(hide_code=True) def _(mo): mo.md(r"""Instantiate upper and lower bounds for state and control""") return @app.cell def _(jnp): x_min = jnp.array([-10.0, -10, -5, -...
Python
1
# Please write a program which estimates a user's typical food expenditure. # # The program asks the user how many times a week they eat at the student cafeteria. Then it asks for the price of a typical student lunch, and for money spent on groceries during the week. # # Based on this information the program calculates...
Python
1
T> { VarA(T), } assert_from_str("10", TestEnum::VarA(10)); } #[test] fn private_in_public_non_generic() { assert_from_str("5", TestStructPrivateInPublic(TestStructPrivate(5))); } #[derive(FromStr, Debug, Eq, PartialEq)] pub struct TestStructPrivateInPublic(TestStructPrivate); #[derive(FromStr, D...
Rust
0
import pandas as pd # Load the two CSV files file1_path = "/u/spa-d4/grad/mfe261/Projects/E2ETOD-In-The-Wild/storage/user_study/sgd_user_study.csv" file2_path = "/u/spa-d4/grad/mfe261/Projects/E2ETOD-In-The-Wild/storage/user_study/sgd_user_study_ourtod.csv" df1 = pd.read_csv(file1_path) df2 = pd.read_csv(file2_path) ...
Python
1
(e.into()), } } _ => Err(Error::UnixTimestamp), } } fn parse_is08601(s: &str) -> Result<NaiveDateTime, Error> { s.parse::<DateTime<Utc>>() .map_or_else(|_| Err(Error::ParseDateTime), |utc| Ok(utc.naive_utc())) } fn parse_rfc2822(s: &str) -> Result<NaiveDateTime, Error> { ...
Rust
0
test() { let mut vm = VM::new(&[]); let init_addr = vm.program_counter; vm.registers[0x0] = 0x10; execute_opcode(&mut vm, OpCode::SEVB(0x0, 0x10)); let next_addr = init_addr + INSTRUCTION_SIZE * 2; // Skips assert_eq!(next_addr, vm.program_counter); execu...
Rust
0
let message = ast::Lit::new(&message); quote! {{ let left = #left; let right = #right; if !(left == right) { let message = String::from_str(#message); message += format!("\nleft: {:?}", left); message += format!("\nright: {:?}...
Rust
0
] { &mut self.next } } <filename>hello-rust/src/main.rs // every Rust program starts with a function main fn main() { // println! is a macro, which means that Rust code // replaces the println! at runtime with actual rust // code that prints to the console println!("Hello, Rust!"); ret...
Rust
0
Batch publish } /// A pubsub subscription. pub struct Subscription<T, Format> where T: DeserializeOwned + Send + 'static, Format: Message<T> + From<pubsub::Message> + Send + 'static, { subscription: Mutex<pubsub::Subscription>, // Helpers to help the compiler see that a subscription can pull a single...
Rust
0
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] struct Entry<V: Val<A>, A: Ord> { // The entry clock tells us which actors edited this entry. clock: VClock<A>, // The nested CRDT val: V, } /// Operations which can be applied to the Map CRDT #[derive(Debug, Clone, PartialEq, Eq, Seriali...
Rust
0
return rate def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: time = max(0, trade_time - start_time) rate = (end - start) / (end_time - start_time) return min(end, start + (rate * time)) def get_pair_params(self, pair: str,...
Python
1
ialized() }; let res = unsafe { libc::pipe(fds.as_mut_ptr()) }; try!(Errno::result(res)); try!(pipe2_setflags(fds[0], fds[1], flags)); Ok((fds[0], fds[1])) } #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "emscripten")))] fn pipe2_setflags(fd1: Raw...
Rust
0
ta["time"]) ax4.plot(times, positions[:, 2], color=colors[controller_name], label=labels[controller_name]) ax4.legend() plt.tight_layout() # 結果を保存 plt.savefig('controller_comparison.png') print("Results saved to controller_comparison.png") ...
Python
1
import re import json def chunk_markdown_by_headers(markdown_text, ideal_word_count=500): """ Splits the markdown content into chunks based on headers. If a chunk's word count is greater than 1.5 * ideal_word_count, splits that chunk into two parts with the same header. Each chunk is represent...
Python
1
ick_on_tuning_table_row_delete_popup() # time.sleep(4) # # toast_message = self.driver.find_element(By.XPATH, "//div[@class='ant-notification-notice-message']") # act_toast = toast_message.text # print(act_toast) # time.sleep(3) # # exp_toast = "Removed filter successfull...
Python
1
import os import pytest from godot import exposed from godot.bindings import Node, OS __current_node = None def set_current_node(node): global __current_node assert __current_node is None __current_node = node def get_current_node(): return __current_node @exposed class Main(Node): def _rea...
Python
1
): self._saw_enospc = True self._maybe_update_progress(line) else: if self._process.poll() is not None: break # Flush any remaining buffered line if buf_bytes: ...
Python
1
import datetime class SpaceRegion: def __init__(self, name, temperature, gravity): self.name = name self.temperature = temperature self.gravity = gravity def get_environmental_features(self): return f"Temperature: {self.temperature}°C, Gravity: {self.gravity}g" class Animal: ...
Python
1
력': weapon_stats_data.get('공격력', 0), '스킬_증폭': weapon_stats_data.get('스킬 증폭', 0), '명중': weapon_stats_data.get('명중', 0), '스피드': weapon_stats_data.get('스피드', 0), '내구도': weapon_stats_data.get('내구도', 0), '방어력': weapon_stats_data.get('방어력', 0), '치명타_확률':...
Python
1
, g_XMTwoPi.v, Mask); Mask = XMVectorGreaterOrEqual(Result, g_XMPi.v); Offset = XMVectorSelect(Offset, g_XMNegativeTwoPi.v, Mask); Result = XMVectorAdd(Result, Offset); return Result; } #[cfg(_XM_ARM_NEON_INTRINSICS_)] { unimplemented!() } #[cfg(_XM_SSE_I...
Rust
0
/native/v1/venue/{venue_id}") assert response.status_code == 200 assert response.json["bannerUrl"] is not None def test_venue_supports_phone_numbers(self, client): invalid_phone_number = "+33594282769" # invalid phone number from real data venue = offerers_factories.VenueFacto...
Python
1
sePixelFormat(hdc, &pfd) { 0 => Err(GlCreationError::OsError(OsErr::last_os_error().to_string(), "Could not get Dummy Pixel Format: {}".to_owned())), f => Ok(f) } } /// Creates a pixel format for the dummy window, selectively taking relevant parts of the /// pixel format to make one that resembles ...
Rust
0
, i32, i32, i32, i32) -> (); /// Returns an index for wasm's `elem.drop`. elem_drop(vmctx, i32) -> (); /// Returns an index for wasm's `memory.copy` memory_copy(vmctx, i32, i64, i32, i64, i64) -> (); /// Returns an index for wasm's `memory.fill` instruction. ...
Rust
0
e.VOLUME_DECREMENT) print("Volume down") last_encoder_state = current_state if count % 1 == 0: # Update brightness_level based on direction and speed brightness_level += direction * BREATH_SPEED # Reverse direction when limits are reached if brightness_...
Python
1
Format::OIHW, group: 2, data: ndarray::arr3(&[[[0.0f32, 1.0]]]).into_dyn(), kernel: tensor4(&[[[[0.0f32]]], [[[0.0]]], [[[0.0]]], [[[0.0]]]]) .into_array::<f32>() .unwrap() .into_dyn(), bias: None, pad: PaddingSpec::Valid, strides: tvec...
Rust
0
CubeMapFace { target, up }| GlobalTransform::identity().looking_at(*target, *up)) .collect::<Vec<_>>(); global_light_meta.gpu_point_lights.clear(); global_light_meta.entity_to_index.clear(); let mut point_lights: Vec<_> = point_lights.iter().collect::<Vec<_>>(); // Sort point lights with shad...
Rust
0
return self.resources.get('riak_solr_searcher_wm') @lazy_property def riak_solr_indexer_wm(self): return self.resources.get('riak_solr_indexer_wm') @lazy_property def riak_kv_wm_counter(self): return self.resources.get('riak_kv_wm_counter') @lazy_property def riak_kv_...
Python
1
![0, 1]; for i in 2..=n { let res = memo[(i - 1) as usize] + memo[(i - 2) as usize]; memo.push(res); } return memo[memo.len() - 1]; } } mod rec { #[allow(dead_code)] pub fn fib(n: u32) -> u32 { match n { n if n < 2 => 1, _ => f...
Rust
0
"') ); } else if split.len() == 4 { res = format!( "0 {} {} * {} {}", split[1].trim_matches('"'), local_to_utc_hour.to_string(), split[2].trim_matches('"'), split[3].trim_matches('"') ); } else { return Err("could not fo...
Rust
0
let mut result = VmTransition::new(1, 0, 2); let current = current_row.iter().map(|&v| BaseElement::new(v)).collect(); let frame = EvaluationFrame::from_rows(current, vec![BaseElement::ZERO; current_row.len()]); result.update(&frame); result } } // Some cases with closures that migh...
Rust
0
; mod handlers; mod models; use actix_web::{web, App, HttpServer}; use dotenv::dotenv; use std::io; use tokio_postgres::NoTls; use crate::handlers::*; #[actix_rt::main] async fn main() -> io::Result<()> { dotenv().ok(); let config = crate::config::Config::from_env().unwrap(); let pool = config.pg.create_pool(No...
Rust
0
"0xbb - USB Transmit Hub Port Endpoint 7"] pub txhubport7: TXHUBPORT7, #[doc = "0xbc - USB Receive Functional Address Endpoint 7"] pub rxfuncaddr7: RXFUNCADDR7, _reserved79: [u8; 1usize], #[doc = "0xbe - USB Receive Hub Address Endpoint 7"] pub rxhubaddr7: RXHUBADDR7, #[doc = "0xbf - USB Rec...
Rust
0
ore than one were found.""" # Legacy compat until 0.6. sa.exc.ConcurrentModificationError = ConcurrentModificationError sa.exc.FlushError = FlushError sa.exc.UnmappedColumnError def _safe_cls_name(cls): try: cls_name = '.'.join((cls.__module__, cls.__name__)) except AttributeError: cls_name =...
Python
1
# merge sort lst = [] # declaring list l n = int(input("Enter number of elements in the list: ")) # taking value from user for i in range(n): temp = int(input("Enter element" + str(i + 1) + ": ")) lst.append(temp) def merge(ori_lst, left, mid, right): L, R = [], [] # PREPARE TWO TEMPORARY LIST TO HO...
Python
1
let y = ring2.from(5); let _ = x == y; } #[test] fn test_add_sub() { let ring1 = ModuloRing::new(&ubig!(100)); let ring2 = ModuloRing::new(&ubig!(_1000000000000000000000000000000)); let test_cases = [ (ring1.from(1), ring1.from(2), ring1.from(3)), (ring1.from(99), ring1.from(5), ring1.f...
Rust
0
Kodi does not work properly without HEAD support. #[actix_web::head("/services/{id}/logo")] async fn head_service_logo( config: actix_web::web::Data<Arc<Config>>, epg: actix_web::web::Data<Addr<EpgActor>>, path: actix_web::web::Path<ServicePath>, ) -> Result<actix_files::NamedFile, Error> { fetch_servi...
Rust
0
= [&[VarLenType::Intn as u8, 8, 8][..]].concat(); dst.extend_from_slice(&header); dst.put_i64_le(val); } ColumnData::F32(Some(val)) => { let header = [&[VarLenType::Floatn as u8, 4, 4][..]].concat(); dst.extend_from_slice(&header)...
Rust
0
ollToken, RawDescriptor, SafeDescriptor, Tube, TubeError, WaitContext, }; use data_model::{DataInit, Le32}; use libc::{recv, MSG_DONTWAIT, MSG_PEEK}; use resources::Alloc; use vm_control::{VmMemoryRequest, VmMemoryResponse}; use vm_memory::GuestMemory; use vmm_vhost::{ connection::socket::Endpoint as SocketEndpoint...
Rust
0
': full_name, #TODO: QUESTION: Do we need this? if so, needs a matching model field on RawResult 'name_slug': slug, } return kwargs def _prep_precinct_result(self, row, office, district, candidate, county, votes): kwargs = self._base_kwargs(row, office, district, can...
Python
1
cApsChanAssociationIpAddressType": cApsChanAssociationIpAddressType, "cApsChanAssociationIpAddress": cApsChanAssociationIpAddress, "cApsExtMIBConformance": cApsExtMIBConformance, "cApsExtGroups": cApsExtGroups, "cApsNotifiesEnableGroup": cApsNotifiesEnableGroup, "cApsConfigPathExt": c...
Python
1
xies = all_proxies[:args.limit] return all_proxies def save_proxies(proxies, output_file): """Save proxies to file""" try: with open(output_file, 'w') as f: for proxy in proxies: if proxy.strip(): f.write(f"{proxy.strip()}\n") print(f"Suc...
Python
1
, I::Pixel: 'static, B: Fn(I::Pixel, I::Pixel, f32) -> I::Pixel, { let (mut x0, mut y0) = (start.0, start.1); let (mut x1, mut y1) = (end.0, end.1); let is_steep = (y1 - y0).abs() > (x1 - x0).abs(); if is_steep { if y0 > y1 { swap(&mut x0, &mut x1); swap(&mut y0...
Rust
0
to_dict(metrics, metric[0]) # append the metric from this micro-batch to global metrics. update_successful, grad_norm, num_zeros_in_grad = self.actor_optimizer.step() data = {"actor/grad_norm": grad_norm} append_to_dict(metrics, data) if update_successful: ...
Python
1
import time import logging from contextlib import contextmanager from typing import Callable, Optional from .base_profiler import BaseProfiler, _thread_local # Supported time functions TIME_FUNCTIONS = { 'execution_time': (time.perf_counter, "high-resolution execution time"), 'cpu_time': (time.process_time, "m...
Python
1
_dim()], // None of the above, keep original color.. _ => colors[ansi], } }, Color::Indexed(idx) => { let idx = match ( config.draw_bold_text_with_bright_colors, flags & Flags::DIM_BOL...
Rust
0
/// * `layer_past` - Unused for BART /// * `attention_mask` - Optional mask of shape (*batch size*, *sequence_length*). Masked position have value 0, non-masked value 1. If None set to 1 /// * `input_embeds` - Unused for BART /// * `token_type_ids` - Unused for BART /// * `position_ids` - Unused for...
Rust
0
USAGE_CONSUMER_CHANNEL_DECREMENT: USAGE = 0x9D; pub const HID_USAGE_CONSUMER_PLAY: USAGE = 0xB0; pub const HID_USAGE_CONSUMER_PAUSE: USAGE = 0xB1; pub const HID_USAGE_CONSUMER_RECORD: USAGE = 0xB2; pub const HID_USAGE_CONSUMER_FAST_FORWARD: USAGE = 0xB3; pub const HID_USAGE_CONSUMER_REWIND: USAGE = 0xB4; pub const HID_...
Rust
0
]), None); // wTotalLength too large assert_eq!(parse_bos(&[0x05, 0x0F, 0x06, 0x00, 0x01]), None); // bNumDeviceCaps == 1 but there are no actual descriptors assert_eq!(parse_bos(&[0x05, 0x0F, 0x05, 0x00, 0x01]), None); // the single capability descriptor too short assert_eq!(parse_bos(&[0x05...
Rust
0
( ((calendar_image.width - textsize) // 2, month_y + 1), weekdays_text, (1, 1, 2), week_font, stroke_width=2, stroke_fill=(1, 1, 1), ) scale_factor = 1.5 cell_size = 30 padding = 15 font = ImageFont.truetype("./SHUKLA/resource/fonts/Montserrat.ttf", ...
Python
1
t the meaning of unsafe, idk what is #[no_mangle] pub unsafe extern "C" fn setvbuf( stream: *mut FILE, buf: *mut c_char, mode: c_int, mut size: size_t, ) -> c_int { let mut stream = (*stream).lock(); // Set a buffer of size `size` if no buffer is given stream.read_buf = if buf.is_null() || s...
Rust
0
i) => i - 1, }; let column = pos - document.lines()[row]; Some(Point { row, column }) } } impl PosFrom<Point> for usize { fn try_pos_from(pos: Point, document: &Document) -> Option<Self> { let Point { row, column } = pos; let idxline = document.lines().get(row)?; ...
Rust
0
src: __m512, a: __m512bh, b: __m512bh, ) -> __m512 { let rst = _mm512_dpbf16_ps(src, a, b).as_f32x16(); let zero = _mm512_setzero_ps().as_f32x16(); transmute(simd_select_bitmask(k, rst, zero)) } #[cfg(test)] mod tests { use crate::{core_arch::x86::*, mem::transmute}; use stdarch_test::...
Rust
0
starting_after: Default::default(), type_: Default::default(), } } } <filename>src/visualization/renderable.rs<gh_stars>0 use bevy::prelude::{Commands, Quat, SpriteBundle, Transform, Vec3}; use crate::engine::agent::Agent; pub trait Render: Agent + Send + Sync + Sized + 'static { //...
Rust
0
ChangeColor(r, g, b) => { println!("Change the color to red {}, green {} and blue {}", r, g, b) } } } // destructure references { struct Point { x: i32, y: i32, } let points = vec![ Point { x: 0, y: 0 }, ...
Rust
0
ires additional authentication when you change the version state of your bucket or you delete and object version adding another layer of security in the event your security credentials are compromised or unauthorized access is granted.", ImpactStatement="", RemediationProcedure="...
Python
1
# Code generated by Lark OpenAPI. import lark_oapi as lark from lark_oapi.api.drive.v1 import * def main(): # 创建client client = lark.Client.builder() \ .app_id(lark.APP_ID) \ .app_secret(lark.APP_SECRET) \ .log_level(lark.LogLevel.DEBUG) \ .build() # 构造请求对象 request: U...
Python
1
from monai.transforms import ( Compose, NormalizeIntensityd, SpatialPadd, CopyItemsd, OneOf, RandCoarseDropoutd, RandCoarseShuffled, ToTensord, NormalizeIntensity, SpatialPad, ) def get_tumor_transforms(roi_size): return Compose( [ NormalizeIntensityd(ke...
Python
1
import os import random from data_crop import listdir def create_txt(txt_name, txt_list): if os.path.exists(txt_name): os.remove(txt_name) with open(txt_name, 'w') as f: for i in txt_list: f.write(i + '\n') f.close() def list2txt(folder, txt_name): list_all = listdir(fold...
Python
1
"""Rename table plans to itineraries Revision ID: 315051f6eb04 Revises: e5f497ae96d5 Create Date: 2024-12-17 22:01:55.751748 """ from typing import Sequence, Union from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision: str = "315...
Python
1
for i in range(3): tem = [0, 2, 4] j = tem[i] target[j] = target[j] - start[i] target[j + 1] = target[j + 1] - start[i] # target[i] = target[i] - start[i] for i in range(len(bboxes)): for j in range(3): tem = [0, 2, ...
Python
1
ing_WinSock\"`*"] pub const IPPORT_TCPMUX: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_WinSock\"`*"] pub const IPPORT_TELNET: u32 = 23u32; #[doc = "*Required features: `\"Win32_Networking_WinSock\"`*"] pub const IPPORT_TFTP: u32 = 69u32; #[doc = "*Required features: `\"Win32_Networking_WinSock\"`*"] pu...
Rust
0
Veniam aliqua velit officia mollit. Qui in dolor mollit veniam exercitation cupidatat eiusmod et officia amet. Velit ea irure aliquip ullamco eu. Id reprehenderit aliquip non veniam veniam adipisicing minim veniam in proident amet sit ea. Ex qui veniam eiusmod officia Lorem Lorem proident sunt dolore culpa nulla ex. Of...
Python
1
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute # Create quantum and classical registers q = QuantumRegister(3, name="q") c = ClassicalRegister(3, name="c") # Create a quantum circuit qc = QuantumCircuit(q, c) # Apply operations as described qc.x(q[0]) # X gate on the first ...
Python
1
from ops.data import OpsClass, OpsField, DszObject, DszCommandObject, cmd_definitions import dsz if ('logonasuser' not in cmd_definitions): dszlogonasuser = OpsClass('logon', {'handle': OpsField('handle', dsz.TYPE_INT), 'alias': OpsField('alias', dsz.TYPE_STRING)}, DszObject) logonasusercommand = OpsClass('log...
Python
1
'); let commands = choices .map(str::trim) .filter(|choice| !choice.is_empty()) .map(|choice| { let tag = T::find(choice); if let Some(tag) = tag { let id = tag.value(); Ok(menu.entries[id].run.clone()) } else if menu.confi...
Rust
0
calc_next_tick() == 0 } pub fn should_draw(&self) -> bool { self.calc_next_frame() == 0 } pub fn mark_tick(&mut self) { self.last_tick = Instant::now(); } pub fn mark_draw(&mut self) { self.last_frame = Instant::now(); } pub fn try_sleep(&self) { let sle...
Rust
0