text
string
label_name
string
labels
int64
from importlib import machinery import sys import types import unittest from .. import util class SpecLoaderMock: def find_spec(self, fullname, path=None, target=None): return machinery.ModuleSpec(fullname, self) def create_module(self, spec): return None def exec_module(self, module):...
Python
1
-> Self { let mut nucl_kmers = CanonicalKmers { k, start_pos: 0, buffer, rc_buffer, }; nucl_kmers.update_position(true); nucl_kmers } fn update_position(&mut self, initial: bool) -> bool { // check if we have enough "physi...
Rust
0
2: money += clicks[click - 1] * 2 else: money += clicks[click - 1] font_money = font_constructor.render(str(money), False, 'white') elif 20 < pos[0] < 306 and 440 < pos[1] < 570: if money > prices_cow[level - 1] or m...
Python
1
data: Bytes(hex!("445566778899").to_vec()), } ); assert!(output.is_success()); } #[test] fn return_with_revert_status() { let output = execute( CODE_RETURN_WITH_DATA, hex!("010000005566778899").to_vec(), MockExt::default(), ...
Rust
0
able to resolve `'Model'` # correctly (as otherwise models would have to be rebuilt even though this # doesn't look necessary). ``` """ def __init__( self, namespaces_tuple: NamespacesTuple | None = None, parent_namespace: MappingNamespace | None...
Python
1
. Dimensionless /// * `as_degrees`:Interprets input and returns output in (deg) if `true` or (rad) if `false` /// /// # Returns /// /// * `anm_ecc`:Eccentric anomaly. Units: (rad) or (deg) /// /// # Examples /// ``` /// use rastro::orbits::anomaly_mean_to_eccentric; /// let e = anomaly_mean_to_eccentric(90.0, 0.001, tr...
Rust
0
r) exit() def cancel(group_id): metadata = get_metadata() if group_id not in metadata: print(f'Item {group_id} does not appear in our records. It must not exist.') print('Existing batch jobs:', sorted(list(metadata.keys()))) return active_jobs = metadata[group_id]['act...
Python
1
ttz_nonzero; return unsafe { cttz_nonzero(x) }; } #[cfg(not(feature = "core_intrinsics"))] { let mut x = x; let mut n = 0; if (x & 0x00000003) == 0 { n += 2; x >>= 2; } if (x & 0x00000001) == 0 { n += 1; } n ...
Rust
0
.completions.clear(); // #[cfg(debug)] // { // debug_cursor_position( // lua, // start_row, // start_col, // rows_deleted, // bytes_deleted, // rows_added, // bytes_added, // cursor, // )?; // } ...
Rust
0
what is the recommended movie? List the movie title only:\n""" movie_recommendation = ask_chatbot(prompt).strip() log(f"Movie recommendation title: {movie_recommendation}") prompt = f"""You are an expert movie bot that recommends movies based on user preferences.\nYou have the following genres available: {g...
Python
1
r = Builder::<TestNetwork, OsRng>::new(0); builder .add_sapling_spend( extsk.clone(), *to.diversifier(), note1, witness1.path().unwrap(), ) .unwrap(); builder ...
Rust
0
, f64); type Axes = (HistAxis, HistAxis, HistAxis, HistAxis); fn axes(&self) -> &Self::Axes { &self.axes } fn bin_at_val(&self, val: Self::Val) -> Self::Bin { ( self.axes.0.bin_at_val(val.0) as u32, self.axes.1.bin_at_val(val.1) as u32, self.axes.2.b...
Rust
0
import pytest @pytest.fixture def cnpj_json(): return { "uf": "SP", "cep": "07115000", "qsa": [ { "pais": None, "nome_socio": "SOCIO_NOME_1", "codigo_pais": None, "faixa_etaria": "Entre XX a XX anos", ...
Python
1
r(GpRegister::Acc, register::GeneralPurpose::with_value(0xaa)) .with_ps_register({ let mut ps = register::ProcessorStatus::default(); ps.carry = true; ps }); let state = cpu.run(2).unwrap(); assert_eq!(0x6001, state.pc.read()); assert_eq!(0xd5, state.acc....
Rust
0
# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai> # # SPDX-License-Identifier: Apache-2.0 import os from unittest.mock import Mock, patch import pytest from requests import HTTPError, RequestException, Timeout from haystack import Document from haystack.components.websearch.serper_dev import Serp...
Python
1
get_script()) .arg("play-file") .arg(&self.output_device) .arg(file) .spawn() .expect("Unable to run script"); self.active_streams.insert(button, command); Ok(()) } fn get_script(&self) -> &str { self.script_path.to_str().unwr...
Rust
0
#!/usr/bin/env python3 # Copyright (c) 2020. Vinci Consulting Corp. 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....
Python
1
maps, image.size) net_attn_maps = return_net_attn_map(net_attn_maps, pipe.tokenizer, prompt) # remove sos and eos net_attn_maps = [attn_map for attn_map in net_attn_maps if attn_map[1].split('_')[-1] != "<<|startoftext|>>"] net_attn_maps = [attn_map for attn_map in net_attn_maps if attn_map[1].split('_...
Python
1
speed=CS.vEgo, freeze_integrator=freeze_integrator) pid_log.active = True pid_log.p = float(self.pid.p) pid_log.i = float(self.pid.i) pid_log.d = float(self.pid.d) pid_log.f = float(self.pid.f) pid_log.output = float(-output_torque) ...
Python
1
class Mobile: def __init__(self, price, brand): self.price = price self.brand = brand self.discount = 0 def purchase(self): total = self.price - self.price * self.discount / 100 print (self.brand, "mobile with price", self.price, "is available after discount at", total) ...
Python
1
32, Location::Imm32(0x80000000), &mut temps, ImmType::None, true, None, ); self.assembler.emit_cmp(Size::S32, tmp, src1); self.assembler .emit_bcond_label(Condition::Ne, label_nooverflow); self.assembler.emit_movn(Si...
Rust
0
uid4()), created_at=int(time.time()), status=Status.COMPLETED, error=None, model=request.model, outputs=forecast_outputs, usage=usage, ) return forecast_response async def forecast( self, request: ForecastReques...
Python
1
assert_eq!(cover.len(), 1); assert_eq!(cover[0], sets[1]); } // Check that even if the limit provides room, we don't include useless items in the soln. #[test] fn exclude_zero_score() { let sets = example_system(); for k in 2..10 { let cover = maximum_cover(...
Rust
0
from __future__ import print_function import sys import zlib import base64 import json _base64_url_charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" _base64_padding = "=" def emit(fd, key, value): # in python3, strings need to be cast into bytes to be passed # into zlib.compress ...
Python
1
im* (1 panes) [layout b5be,173x42,0,0,1]"; let window = Window::from_line(line).unwrap(); assert_eq!(window.layout, "b5be,173x42,0,0,1") } } <gh_stars>0 use crate::msg::QueryAnswer; use crate::stake::{calculate_rewards, shares_per_token}; use crate::state::ReadonlyBalances; use crate::state_staking:...
Rust
0
import asyncio import threading from common.utils.push_notification_auth import PushNotificationReceiverAuth from starlette.applications import Starlette from starlette.requests import Request from starlette.responses import Response import traceback class PushNotificationListener(): def __init__(self, host, po...
Python
1
MC_TR register accessor: an alias for `Reg<SDRAMC_TR_SPEC>`"] pub type SDRAMC_TR = crate::Reg<sdramc_tr::SDRAMC_TR_SPEC>; #[doc = "SDRAMC Refresh Timer Register"] pub mod sdramc_tr; #[doc = "SDRAMC_CR register accessor: an alias for `Reg<SDRAMC_CR_SPEC>`"] pub type SDRAMC_CR = crate::Reg<sdramc_cr::SDRAMC_CR_SPEC>; #[d...
Rust
0
to: H160, /// Transfered Value value: U256, /// Gas gas: U256, /// Input data input: Bytes, /// The type of the call. call_type: CallType, } impl From<trace::Call> for Call { fn from(c: trace::Call) -> Self { Call { from: c.from, to: c.to, value: c.value, gas: c.gas, input: c.input.into(), ...
Rust
0
::R) reader structure"] impl crate::Readable for SYSCON_FLASH_ACE2_ADDR {} #[doc = "`write(|w| ..)` method takes [syscon_flash_ace2_addr::W](syscon_flash_ace2_addr::W) writer structure"] impl crate::Writable for SYSCON_FLASH_ACE2_ADDR {} #[doc = "SYSCON_FLASH_ACE2_ADDR"] pub mod syscon_flash_ace2_addr; #[doc = "SYSCON_...
Rust
0
(c) 2016-2021 Memgraph Ltd. [https://memgraph.com] // // 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...
Rust
0
_VERSION_PATCH_MASK_KHR } #[inline] pub fn make_version_khr( major: cl_version_khr, minor: cl_version_khr, patch: cl_version_khr, ) -> cl_version_khr { ((major & CL_VERSION_MAJOR_MASK_KHR) << (CL_VERSION_MINOR_BITS_KHR + CL_VERSION_PATCH_BITS_KHR)) | ((minor & CL_VERSION_MINOR_MASK_KHR) << CL_V...
Rust
0
case other: print('Ha digitado una opción invalida ') os.system("pause") except ValueError: print('Digitacion incorrecta, intentelo de nuevo') def manejo_ventas(): while True: try: os.system('cls') print('MANEJO VENT...
Python
1
stId @RequestId.setter def RequestId(self, RequestId): self._RequestId = RequestId def _deserialize(self, params): self._RequestId = params.get("RequestId") class AttachUserPolicyRequest(AbstractModel): """AttachUserPolicy请求参数结构体 """ def __init__(self): r""" ...
Python
1
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt """Contains logic for retrieving special methods. This implementation does not r...
Python
1
CachedMir::Ref(r) => r, CachedMir::Owned(ref rc) => &rc, } } } fn main() { } use anyhow::Result; use mongodb::{bson::doc, Database}; use crate::db::{find_all, find_one}; use crate::util::format_url; use super::models::{Included, Response, Spacecraft}; pub async fn find_spacecraft_detail(db: ...
Rust
0
ait Copy {} fn foo() {} fn bar<T: Copy>(T) -> T {} struct Struct(usize); enum Enum { Variant(usize) } trait Test { fn test(&self) -> bool; } impl<T: Copy> Test for T {} fn test() { foo.test(); bar.test(); Struct.test(); ...
Rust
0
}<filename>tests/integrations/config/dynamic/pessimistic_txn.rs<gh_stars>1-10 use std::sync::{mpsc, Arc}; use std::time::Duration; use security::SecurityManager; use test_violetabftstore::TestFidelClient; use edb::config::*; use edb::server::lock_manager::*; use edb::server::resolve::{Callback, StoreAddrResolver}; us...
Rust
0
# You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). # You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. # Example 1: # Input: matrix = [[1,2,3],[4,5,6],[7,8,9...
Python
1
"""Script for starting up a python module emulator.""" import logging import asyncio from argparse import ArgumentParser from typing import Dict, Callable from typing_extensions import Final from opentrons.hardware_control.emulation.abstract_emulator import AbstractEmulator from opentrons.hardware_control.emulation.he...
Python
1
""" Comprehensive example: Ranking publications in a citation network using paperank with the frontier-based crawler (crawl_and_rank_frontier). This script illustrates an end-to-end workflow: 1. Starting from one or more seed DOIs, it iteratively expands a symmetric 1-hop frontier (both citations and references...
Python
1
py_get.push(t); } } py_get.to_lowercase() } const PY_CODE: [&'static str; 399] = [ "a :阿啊吖嗄腌锕", "ai :爱埃碍矮挨唉哎哀皑癌蔼艾隘捱嗳嗌嫒瑷暧砹锿霭", "an :安按暗岸案俺氨胺鞍谙埯揞犴庵桉铵鹌黯", "ang :昂肮盎", "ao :凹奥敖熬翱袄傲懊澳坳拗嗷岙廒遨媪骜獒聱螯鏊鳌鏖", "ba :把八吧巴拔霸罢爸坝芭捌扒叭笆疤跋靶耙茇...
Rust
0
= hddlZejdZgdZddj eZej dedZeejdjy) N(oDKYFa3FOakn5QS0gTNtz6Nbjy9IxeA5TMLILPQt)Mountain WildernessForestHighlandzExplain ...
Python
1
0), (4, 1, 10), (5, 1, 10), (6, 1, 10)]) .build() .execute_with(|| { for i in 3..7 { assert_ok!(Stake::leave_nominators(Origin::signed(i), 1u32),); } }); } #[test] fn payouts_follow_nomination_changes() { ExtBuilder::default() .with_balances(vec![ (1, 100), (2, 100), (3, 100), (4, 100), ...
Rust
0
id::from_raw(unimplemented!())).unwrap(); let local_state = state.clone(); tokio::spawn(async move { loop { local_state.lock().await.tick().await; tokio::time::delay_for(Duration::from_secs(10)).await; } }); let service_fun = make_service_fn(move |_| { ...
Rust
0
t_rune_t = ::libc::c_int; #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed1 { pub _bindgen_data_: [u64; 16usize], } impl Union_Unnamed1 { pub unsafe fn __mbstate8(&mut self) -> *mut [::libc::c_char; 128usize] { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transm...
Rust
0
# p4.py —— 三架无人机各投一枚;优化三机并集遮蔽时长 import math, itertools import numpy as np, pandas as pd from dataclasses import dataclass from typing import List, Optional # ===== 常量 ===== g = 9.8 v_missile = 300.0 cloud_sink = 3.0 R = 10.0 # 导弹 / 目标 M0 = np.array([20000., 0., 2000.]) DECOY= np.array([0., 0., 0.]) T = np.array(...
Python
1
e::convert::{DivMeasure, MulMeasure}; use crate::unit::Unit; use crate::Measure; use std::cmp::Ordering; use std::fmt::Formatter; use std::ops::{Div, Mul}; struct USome; impl Unit for USome {} type SomeUnit<N> = Measure<N, USome>; struct USomeMul; impl Unit for USomeMul {} ...
Rust
0
[{cid}] += experience\n\n' out_str += f'\n@settle_behavior.add_settle_behavior_effect(constant.BehaviorEffect.{large_str})' out_str += f'\ndef handle_target_add_large_{skill}(character_id: int, add_time: int, change_data: game_type.CharacterStatusChange, now_time: int):' out_str += f...
Python
1
gger.error(f"群boss生成推送失败:{e}") @boss_help.handle() async def _(bot: Bot, event: GroupMessageEvent): await data_check_conf(bot, event) msg = __boss_help__ msg = await pic_msg_format(msg, event) pic = await get_msg_pic(msg) await boss_help.finish(MessageSegment.image(pic)) @boss_del...
Python
1
, Some(&2)); assert_eq!(end_state.get(&2), Some(&1)); assert_eq!(end_state.get(&6), Some(&1)); assert_eq!(end_state.get(&8), Some(&1)); } #[test] fn it_calculates_the_number_of_fish_after_18_days() { let input = "3,4,3,1,2"; let initial_state: Vec<u8> = input ...
Rust
0
mem.store_syllables(reg, 1); mem.push(reg); assert_eq!(mem.stack, vec![1]); let reg = Register::Register1; mem.store_syllables(reg, 2); mem.push(reg); assert_eq!(mem.stack, vec![1, 2]); } #[test] fn alliteration() { let alliteration_program = r#" ...
Rust
0
rbotconfig.access_token = server_config.access_token.clone(); } if let Some(bots_config) = &self.bots { if let Some(bot_config) = bots_config.get(bot_id) { if !bot_config.superusers.is_empty() { rbotconfig.superusers = bot_config.superusers.c...
Rust
0
def receberPalavras(): while True: try: palavra = input('Informe uma palavra') if isValid(palavra): return palavra except ValueError: print('Ocorreu um erro, tente novamente!') def isValid(palavra): if len(palavra) == 0: return False ...
Python
1
from django.urls import path from . import views urlpatterns = [ path('', views.all_chai, name='all_home'), path('movies/', views.movie_list, name='all_movies'), path('movies/<int:pk>', views.movies_details, name='movie-details'), ]
Python
1
} #[test] fn add_event_source_mutator_test() { let mut l = EventMultiplexer::new().unwrap(); let h = MutatorTestHandler(EventFd::new().unwrap()); assert!(l.handlers.is_empty()); AddEventSourceMutator(Some(Box::new(h))) .mutate(&mut l) .unwrap(); ...
Rust
0
th lower terms added from GC shadowing those with the same indices /// but with higher terms. pub term: u64, pub ctx: Vec<u8>, pub file_id: u64, pub block_offset: usize, pub block_len: usize, pub offset: usize, pub len: usize, } pub struct MemState { first_index: u64, mask_index...
Rust
0
expected_output = { 'global_mld_snooping_configuration': { 'mld_snooping': 'Disabled', 'global_pim_snooping': 'Disabled', 'mldv2_snooping': 'Disabled', 'listener_message_suppression': 'Disabled', 'tcn_solicit_query': 'Disabled', 'tcn_flood_query_count': ...
Python
1
_AnchorToNeighbour(AObj: usize, ASide: TAnchorKind, ASpace: i32, ASibling: usize); pub fn TabSheet_AnchorParallel(AObj: usize, ASide: TAnchorKind, ASpace: i32, ASibling: usize); pub fn TabSheet_AnchorHorizontalCenterTo(AObj: usize, ASibling: usize); pub fn TabSheet_AnchorVerticalCenterTo(AObj: usize, ASibling: us...
Rust
0
) .build(); let t = sled::Tree::start(config).unwrap(); for i in 0..N_PER_THREAD { let k = kv(i); t.set(k.clone(), k).unwrap(); } for (i, (k, v)) in t.iter().map(|res| res.unwrap()).enumerate() { let should_be = kv(i); assert_eq!(should_be, k); assert_eq!...
Rust
0
use std::{fmt, mem, str}; use std::iter::IntoIterator; use std::ffi::{self, CString}; use std::ops::{Deref, DerefMut}; pub use kind::TypeKind; /// The integer representation of a type pub mod kind { use libc::c_int; bitflags! { pub struct TypeKind: c_int { const Void = 0; const ...
Rust
0
\ void verify_##T() { \ int yEnd = (gDimY != 0) ? gDimY: 1; \ int zEnd = (gDimZ != 0) ? gDimZ: 1; \ for (int x=0; x < gDimX; x ++) { \...
Rust
0
n_voice_toggle.setText("🌐 火山引擎 (关)") self.ui.btn_voice_toggle.setStyleSheet("background-color: #f44336; color: white;") else: # 禁用语音控制 self.voice_controller.disable_voice_control() self.ui.textEdit_results.append("⏹️ 火山引擎语音控制已禁用") ...
Python
1
=> "\u{02102}", "cong;" => "\u{02245}", "congdot;" => "\u{02A6D}", "Congruent;" => "\u{02261}", "Conint;" => "\u{0222F}", "conint;" => "\u{0222E}", "ContourIntegral;" => "\u{0222E}", "Copf;" => "\u{02102}", "copf;" => "\u{1D554}", "coprod;" => "\u...
Rust
0
LINK_PARK_CH0_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:19 - This register stores the 20 least significant bits of the first outlink descriptor's address."] #[inline(always)] pub fn outl...
Rust
0
/ All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. //! Data Protection API Prototypes and Definitions // This header file provides the definitions and symbols necessary for an // Application or Smart Card Service Provider to access the Smartca...
Rust
0
{ size: 10, style: String::from("sneaker"), }, Shoe { size: 13, style: String::from("sandal"), }, Shoe { size: 10, style: String::from("boot"), }, ]; let in_my_size = shoes_in_my_size(shoes, 10); ...
Rust
0
l in payload_code += "\t\t%s = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(%s)),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n" %(fpName,shellcodeBufName) # virtual lock to prevent the memory from paging out to disk payload_code += "\t\tctypes.windll.kernel32.VirtualLock(cty...
Python
1
# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction # Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han # International Conference on Computer Vision (ICCV), 2023 from functools import partial import torch.nn as nn from ..utils import build_kwargs_from_config __all__ = ["build_act"] ...
Python
1
check_order.sort_by_key(|(_fmt, t)| { let $ty = *t; (!($prio)) as u8 }); }}; } //Priorize filetype match (in_name, in_ext) { ("osu!", "db") => priorize!(Type(ty) => ty == FileType::Listing), ("collection", "db") => priorize!(Type(...
Rust
0
_m, tx_fee_info.min_fee, tx_fee_info.max_fee, tx_fee_info.fee_mc); // at this point, cust/merch have both exchanged initial sigs (escrow-tx + merch-close-tx) let funding_tx_info = generate_test_txs(&mut rng, b0_cust, b0_merch); // set escrow-tx and merch-close-tx info cust_state.set_in...
Rust
0
@property def pipeline_class(self) ->Union[Callable, DiffusionPipeline]: raise NotImplementedError( 'You need to set the attribute `pipeline_class = ClassNameOfPipeline` in the child test class. See existing pipeline tests for reference.' )
Python
1
sult = general_message(status, "sync share event", msg, bean=data.to_dict()) return Response(result, status=status) except PluginShareRecordEvent.DoesNotExist: result = general_message(404, "not exist", "分享事件不存在") return Response(result, status=404) class PluginShareComple...
Python
1
ther canister, a canister `spend`s //! cycles in the following three ways: //! a) executing messages, //! b) sending messages to other canisters, //! c) storing data over time/rounds //! Each of the above spending is done in three phases: //! 1. reserving maximum cycles the operation can require //! 2. executing the op...
Rust
0
pub fn kill_process_by_name(process_name: &str) { let process_id = get_process_id_by_name(process_name).unwrap(); let process = unsafe { OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, false, process_id) }; unsafe { TerminateProcess(process, 0) }; } pub fn convert_windows_string<'a, const N:...
Rust
0
level) root_logger.addHandler(file_handler) except (PermissionError, OSError) as e: console.print(f"[red]Error creating log file {config.file}: {e}[/red]") raise # Console handler (only if console_level is set) if config.console_level is not None: ...
Python
1
_R { SAMP_DL_SW_R::new((self.bits & 0x3f) as u8) } } impl W { #[doc = "Bit 15 - Sample Delay Calibration Start"] #[inline(always)] pub fn samp_dl_cal_start(&mut self) -> SAMP_DL_CAL_START_W { SAMP_DL_CAL_START_W { w: self } } #[doc = "Bit 7 - Sample Delay Software Enable"] #[...
Rust
0
er_client)?; Ok(()) } fn test_list_volumes(client: &ControllerClient) -> DatenLordResult<()> { let vol_names = (1..5) .map(|idx| format!("tmp_volume_name_{}", idx)) .collect::<Vec<_>>(); // Test create new volume let mut vc = VolumeCapability::new(); ...
Rust
0
let builder = move || -> server::ServerCore { let setup = plonk::SetupForProver::prepare_setup_for_prover( circuit_base.clone(), reader::load_key_monomial_form(&srs_monomial_form), reader::maybe_load_key_lagrange_form(srs_lagrange_form), ) .expect("prepare err...
Rust
0
_) => num.parse().expect("couldn't parse DB_TIMEOUT"), (_, Env::Production) => 10, (_, Env::Test) => 1, _ => 30, }; let thread_pool = Arc::new(ScheduledThreadPool::new(db_helper_threads)); let diesel_db_config = r2d2::Pool::builder() .max_size(d...
Rust
0
specified directory is excluded from searching pub fn is_excluded(&self, path: impl AsRef<Path>) -> bool { let path = path.as_ref(); #[cfg(target_family = "windows")] let path = Common::normalize_windows_path(path); // We're assuming that `excluded_directories` are already normalize...
Rust
0
) } } Ok(keyinputs) } fn remap_to_keybind( &self, from: super::KeyInput, action: super::Action, ) -> Result<Box<dyn KeyBind<K, M, C> + 'a>, InvalidConfigError> { match action { super::Action::KeyInput { to, with: _ } => Ok(Box::new(crate::Keymap::new( self.into_dom...
Rust
0
lace(Some(board_btn)); }); loop { continue; } } loop { continue; } } #[interrupt] fn EXTI15_10() { free(|cs| { let mut btn_ref = BUTTON.borrow(cs).borrow_mut(); if let Some(ref mut btn) = btn_ref.deref_mut() { if btn.check_interr...
Rust
0
ge(&packed).await.expect(ERR_UNPACK); assert_eq!(unpacked, msg); assert_eq!(p_recip, recip_key.encoded_verkey().unwrap()); assert_eq!(p_send, None); } pub async fn db_keypair_pack_unpack_auth<DB: Backend>(db: &Store<DB>) { let mut conn = db.session(None).await.expect(ERR_SESSION); let sender_key =...
Rust
0
import pygame import math pygame.init() screen = pygame.display.set_mode((300,300)) clock = pygame.time.Clock() player_surf = pygame.surface.Surface((50,50)) player_surf.fill("Red") player_rect = player_surf.get_rect() player_rect.center = (150,150) # TODO: naimplementuj chytrou (s rychlosti padu, ktera se meni v ...
Python
1
''' Kattis - playfair Another kinda timewasting problem. Just use whatever means necessary to solve since this isn't a very time critical problem. Be careful not to miss out any of the cases. Time: O(length of plain text), Space: O(length of plain text) ''' key = input() alphabet = list("abcdefghijklmnoprstuvwxyz") sq...
Python
1
om_args(vec!["kafcat", "-C", "-b", "localhost", "-t", "topic", "-e"]); assert_eq!( config.consumer_kafka.unwrap(), KafkaConsumerConfig { brokers: "localhost".to_string(), group_id: "kafcat".to_string(), offset: KafkaOffset::Beginning, ...
Rust
0
py for DISPLAYCONFIG_ADAPTER_NAME {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DISPLAYCONFIG_ADAPTER_NAME { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: 'Win32_Devices_Display', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub struct ...
Rust
0
getstyle::*; #[derive(Clone)] pub struct Splitter { pub axis: Axis, pub align: SplitterAlign, pub pos: f32, pub min_size: f32, pub split_size: f32, pub bg: Quad, pub animator: Animator, pub realign_dist: f32, pub split_view: View, pub _split_area: Area, pub _calc_pos: f...
Rust
0
} } pub enum GuiMsg { SetWindowOpen { window: Windows, open: Option<bool> }, SetLightMode, SetDarkMode, EguiEvent(egui::Event), FileDropped { path: std::path::PathBuf }, Cut, Copy, Paste, // TODO this shouldn't really be here, as things like the console // will never upda...
Rust
0
# -*- coding: utf-8 -*- # © 2014-2015 Antiun Ingenieria, SL (Madrid, Spain, http://www.antiun.com) # Antonio Espinosa <antonioea@antiun.com> # Daniel Gómez-Zurita <danielgz@antiun.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Website sale categories me...
Python
1
-> &str { let mut rand = thread_rng(); let random_index = rand.gen_range(0..self.answers.len()); self.answers[random_index].as_str() } } use bloom_filter_simple::{BloomFilter, DefaultBloomFilter, SeededBloomFilter}; use std::time::Instant; #[test] #[ignore] fn measure_inserting_km() {...
Rust
0
import torch import torch.nn as nn import torch.nn.functional as F from .resnet_encoder import * class RectifyNet(nn.Module): def __init__(self, num_layers=18, pretrained=True): super(RectifyNet, self).__init__() self.encoder = ResnetEncoder( num_layers=num_layers, pretrained=pretraine...
Python
1
DFSamplePacket}; use crate::sampler::Sample; use crate::{Float, Spectrum, Vec3, PACKET_SIZE}; use serde::{Deserialize, Serialize}; #[derive(Default, Serialize, Deserialize)] pub struct BSDF { #[serde(default)] bxdfs: Vec<Box<dyn BxDF>>, } impl BSDF { pub fn new(bxdfs: Vec<Box<dyn BxDF>>) -> Self { ...
Rust
0
) { if !meets_msrv(msrv.as_ref(), &msrvs::POINTER_CAST) { return; } if_chain! { if let ExprKind::Cast(cast_expr, cast_to_hir_ty) = expr.kind; let (cast_from, cast_to) = (cx.typeck_results().expr_ty(cast_expr), cx.typeck_results().expr_ty(expr)); if let ty::RawPtr(TypeAndMut ...
Rust
0
lf.obj = Some(UnixSocketObject::create(path)?); Ok(()) } /// Server 3: Listen to a socket pub fn listen(&mut self) -> Result<(), Error> { self.status = Status::Listening; Ok(()) } /// Server 4: Accept a connection on listening. pub fn accept(&mut self) -> Result<UnixSoc...
Rust
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 applicable law or agreed to in writing, software # distributed under th...
Python
1
> 3: fourth_line = output.split('\n')[3] if len(fourth_line.split(' ')) > 3: R_1 = float(fourth_line.split(' ')[3]) else: print("Error: Not enough words in the fourth line.") else: print("Error: Not eno...
Python
1
e() } } impl ::std::fmt::Display for WebSocketOutboundSettings { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for WebSocketOutboundSettings { type RuntimeType = ::protobuf::reflect::rt...
Rust
0
[garden_data[garden_data['season'] == s]['happiness_score'].values for s in seasons] bp = ax5.boxplot(season_happiness, labels=seasons, patch_artist=True, notch=True, widths=0.6) for patch, color in zip(bp['boxes'], [PASTEL_EASTER['mint'], PASTEL_EASTER['sky'], PASTEL_EASTER['coral']]...
Python
1
AKEY_SPEC>; #[doc = "AES accelerator key register"] pub mod aesakey; #[doc = "AESADIN register accessor: an alias for `Reg<AESADIN_SPEC>`"] pub type AESADIN = crate::Reg<aesadin::AESADIN_SPEC>; #[doc = "AES accelerator data in register"] pub mod aesadin; #[doc = "AESADOUT register accessor: an alias for `Reg<AESADOUT_S...
Rust
0