text
string
label_name
string
labels
int64
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: dic = {} ans = [] for ind, i in enumerate(numbers): dic[i] = ind for ind,i in enumerate(numbers): if target-i in dic: ans.append(ind+1) ...
Python
1
e\xcc\xd6-\xae\x85\xc1\xd6\xfd(\xa6H\x0fab\xd8\ \xb7\xaf\x17\x95\x1b\xacM)\xcb\x823\x1a\xc4\x83I#\ 1\xdf<]\xe3U\x84\xdep\xd9_2\x10pV\xcb\ aJ\x19\xf0\x1d\x9b\x0bw\xa1\x15\x0f\xcen\x9b\xc8@\ \x88\x08\x0a\xc2d\xe0S\x7f\x9f\xfd\xd8\xcf\xe5!\xe9\xec\ \x11\xb4\x8e!\xcbQ`\xbc\x91\x06\x91\xf7\xc1l\x15a\ \x01&\x03\xf4\xc7\x19\x...
Python
1
from __future__ import annotations import warnings import pytest from datashader.macros import expand_varargs import inspect from numba import jit # Example functions to test expand_varargs on def function_no_vararg(a, b): return a + b def function_with_vararg(a, b, *others): return a + b - function_no_var...
Python
1
# Copyright (c) Facebook, Inc. and its affiliates. # 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 os import glob import numpy as np import torch def make_test_pth(seq_dir, frame_sel_idx): rgb_paths, d_paths,...
Python
1
pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Pad 33 functi...
Rust
0
Peripheral, ..Default::default() }); } else if #[cfg(sdmmc_v2)] { regs.idmabase0r().write(|w| w.set_idmabase0(buffer as *mut u32 as u32)); regs.idmactrlr().modify(|w| w.set_idmaen(true)); } } regs.dctrl().modify...
Rust
0
reak return urls def get_total_price_of_all_books(urls: list) -> float: """ Calcule le prix total de tous les livres (prix * quantité en stock) sur toutes les pages à partir d'une URL de départ. :param urls: URLs à scrapper :return: Prix total de tous les livres """ total_price = 0.0 ...
Python
1
xywh'), # 降低框回归影响 # dict(type='IoUCost', iou_mode='giou', weight=1.5) # 适当降低IoU权重 # ])), # train_cfg=dict( # assigner=dict( # type='HungarianAssigner', # match_costs=[ # dict(type='BinaryFocalLossCost', weight=2.5), # 适度增强分类权重 # ...
Python
1
nan, np.nan, -0.01, -0.2, -0.22, -0.18, -0.16, -0.07], [0.23, 0.0, np.nan, -0.06, -0.07, -0.21, -0.24, -0.25, -0.23, -0.13], [-0.05, -0.11, 0.0, 0.1, -0.19, -0.23, -0.23, -0.18, -0.19, -0.16], [-0.19, -0.05, 0.13, -0.08, -0.22, -0.23, -0.26, -0.15, -0.12, -0.13], [-0.2, -...
Python
1
import collections class Solution: def minWindow(self, s: str, t: str) -> str: h_m = collections.defaultdict(int) m = len(t) for c in t: h_m[c] += 1 best = float('inf') st, en, ss, start = 0, 0, 0, 0 while en < len(s): if s[e...
Python
1
#!/usr/bin/env python3 from typing import List # time: O(n), space: O(1) class Solution: def countSeniors(self, details: List[str]) -> int: count = 0 for passenger in details: if int(passenger[11] + passenger[12]) > 60: count += 1 return count print(Solution(...
Python
1
from __future__ import print_function import time import numpy as np import sys import gym from PIL import Image from gibson.core.render.profiler import Profiler from gibson.envs.husky_env import * from gibson.envs.ant_env import * from gibson.envs.humanoid_env import * from gibson.envs.drone_env import * import pybull...
Python
1
import os import typer from dotenv import load_dotenv, find_dotenv import quack2tex app = typer.Typer(invoke_without_command=True) @app.command() def start( gemini_api_key: str = typer.Option(None, envvar="GEMINI_API_KEY", help="Google Gemini API key"), openai_api_key: str = typer.Option(None, envvar="OPEN...
Python
1
import dataclasses import inspect from typing import Callable, Generic, TypeVar T = TypeVar("T") @dataclasses.dataclass class PyCtxPointer(Generic[T]): ancestors: list[T] current: tuple[T] | None pass class PyCtx(Generic[T]): """React-like context for Python. A consumer may access context values fr...
Python
1
ion_max) < 1 or int(lsa_generation_max) > 60: raise OspfParamsError('lsa_generation_max') if params.get('lsa_generation_min'): if int(lsa_generation_min) < 10 or int(lsa_generation_min) > 60000: raise OspfParamsError('lsa_generation_min') if params.get('lsa_...
Python
1
import sys import os backend_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.insert(0, backend_path) from app.Services.students_plans_info_services import StudentPlanInfoService from stable_baselines3 import PPO from stable_baselines3.common.env_util import make_vec_env from LSTMPredict...
Python
1
: (usize, &&[u8])| { v2.iter().enumerate().for_each(|(index3, v3)| { let new_index = (y + x*shape[1])*3 + index3; vec[new_index] = *v3; }); }); }); return vec; } fn fine_mapping() -> Result<(), Box<dyn Error>>{ ...
Rust
0
"""Tests for Vanderbilt SPC component.""" from unittest.mock import Mock, PropertyMock, patch from homeassistant.bootstrap import async_setup_component from homeassistant.components.spc import DATA_API from homeassistant.const import STATE_ALARM_ARMED_AWAY, STATE_ALARM_DISARMED from homeassistant.core import HomeAssis...
Python
1
#[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Pad 33 input enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD33INPEN_A { #[doc = "0: Pad i...
Rust
0
from typing import Dict, List, Any, Optional, Callable from dataclasses import dataclass from enum import Enum import asyncio from loguru import logger class ReasoningState(str, Enum): """Estados del proceso de razonamiento""" INITIALIZING = "initializing" ANALYZING = "analyzing" PLANNING = "planning" ...
Python
1
from helpers import get_response_pydantic, extend_contents from pydantic_models.summarization import StepSummarySchema def get_step_summary_v4(contents, steps, task): if len(steps) == 0: return None if len(steps) == 1: steps = f"step `{steps[0]}`" else: steps = "steps ```\n" + '; ...
Python
1
ocess_fn( preprocess_spec, word_vocab=word_vocab, tag_vocab=tag_vocab, label_distribution_shift=False, ) preprocessed_ds = normal_preprocess_fn(ds) for _, label in preprocessed_ds: label_sum = tf.reduce_sum(label, axis=0) self.assertEqual(tf.shape(label_sum), [tag...
Python
1
pub outset: crate::Reg<outset::OUTSET_SPEC>, #[doc = "0x50c - Clear individual bits in GPIO port."] pub outclr: crate::Reg<outclr::OUTCLR_SPEC>, #[doc = "0x510 - Read GPIO port."] pub in_: crate::Reg<in_::IN_SPEC>, #[doc = "0x514 - Direction of GPIO pins."] pub dir: crate::Reg<dir::DIR_SPEC...
Rust
0
# -*- coding: utf-8 -*- # # Copyright 2022 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
Python
1
value, parsed_value); } #[test] fn bool_should_work() { round_trip(&true); round_trip(&false); } #[test] fn u8_should_work() { round_trip(&1u8); } #[test] fn u32_should_work() { round_trip(&1u32); } #[test] fn i32_should_work() { ...
Rust
0
ttr = attributes[attrName] except IndexError: sys.stderr.write('Could not match attribute "{}" for particle {} with any defined attributes. Skipping.\n'.format(attrName, pnum)) continue if len(value) != attr.count: sys.stderr.wr...
Python
1
::spawn(async move { loop { task::sleep(Duration::from_secs(1)).await; println!("abc"); } }); loop { task::sleep(Duration::from_secs(1)).await; } } async fn async_main() { let f1 = task::spawn(loop_print()); let f2 = task::spawn(loop_print2()); ...
Rust
0
::Result { self.lit().u8(value) } pub fn u16(self, value: u16) -> F::Result { self.lit().u16(value) } pub fn u32(self, value: u32) -> F::Result { self.lit().u32(value) } pub fn u64(self, value: u64) -> F::Result { self.lit().u64(value) } pub fn f32<S>(...
Rust
0
Fn(&P) -> bool + Send + Sync + 'static) = transmute(f); f(&Bin::from_glib_borrow(this).downcast_unchecked()).to_glib() } unsafe extern "C" fn element_added_trampoline<P>(this: *mut ffi::GstBin, element: *mut ffi::GstElement, f: glib_ffi::gpointer) where P: IsA<Bin> { let f: &&(Fn(&P, &Element) + Send + Sync + ...
Rust
0
istics(env) env = NoopResetEnv(env, noop_max=30) env = MaxAndSkipEnv(env, skip=cfg.env_frameskip) env = EpisodicLifeEnv(env) # noinspection PyUnresolvedReferences if "FIRE" in env.unwrapped.get_action_meanings(): env = FireResetEnv(env) env = ClipRewardEnv(env) env = gym.wrappers.Res...
Python
1
"xml" => ContentType::XML, _ => ContentType::TEXT, } } pub fn value(&self) -> &str { match *self { ContentType::CSS => "text/css", ContentType::GIF => "image/gif", ContentType::HTML => "text/html", ContentType::JPEG => "im...
Rust
0
::Error::custom)?; let g = GraphUpdate { changesets: Mutex::new(changesets), event_counter, serialization, }; Ok(g) } } impl<'de> Deserialize<'de> for GraphUpdate { fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error> where ...
Rust
0
import argparse import statistics import habitat import habitat.habitat_cuda as hc from habitat.analysis.metrics import Metric from habitat.profiling.kernel import KernelProfiler def measure_peak_flops(profiler): results = profiler.measure_kernels(hc._diagnostics.run_flop_test) assert len(results) == 1 k...
Python
1
low::ARRAY_BUFFER, self.buffer_vertices); gl.vertex_attrib_pointer_f32(*e, 3, glow::FLOAT, false, 0, 0); } } if let Some(e) = location_normals { unsafe { gl.bind_buffer(glow::ARRAY_BUFFER, self.buffer_normals); gl.vertex_attrib_poin...
Rust
0
, vks: &[&VerifyingKeyVar<E>], challenges: &ChallengesFpElemVar<F>, poly_evals: &[FpElemVar<F>; 3], batch_proof: &BatchProofVar<F>, alpha_bases: &[FpElemVar<F>], non_native_field_info: NonNativeFieldInfo<F>, ) -> Result<(ScalarsAndBasesVar<F>, Vec<FpElemVar<F>>), PlonkError> where E: Pairing...
Rust
0
"""任务规则关联模型""" from sqlalchemy import Column, Integer, ForeignKey, Boolean, DateTime, func from sqlalchemy.orm import relationship from app.database import Base class TaskRuleAssociation(Base): """任务规则关联表 - 多对多关系""" __tablename__ = "task_rule_associations" id = Column(Integer, primary_key=True, index...
Python
1
3]([0], [4]) log(&format!("//REL {}({}, {})", stimulus_words[3], stimulus_words[0], stimulus_words[4])); log(&format!("{}({}, {}).", stimulus_words[3], stimulus_words[0], stimulus_words[4])); extracted_relations.push(Relation { head: stimulus_...
Rust
0
#!/usr/bin/env python # Indents a CAF log with trace verbosity. The script does *not* deal with a log # with multiple threads. # usage (read file): indent_trace_log.py FILENAME # (read stdin): indent_trace_log.py - import argparse, sys, os, re def is_entry(line): return 'TRACE' in line and 'ENTRY' in line ...
Python
1
class DashTestingError(Exception): """Base error for pytest-dash.""" class InvalidDriverError(DashTestingError): """An invalid selenium driver was specified.""" class NoAppFoundError(DashTestingError): """No `app` was found in the file.""" class DashAppLoadingError(DashTestingError): """The dash a...
Python
1
r""" Multi-server setup Installation requirements: pip install trame trame-vuetify """ import asyncio from trame.app import get_server from trame.ui.vuetify import SinglePageLayout from trame.widgets import vuetify server1 = get_server("server1", client_type="vue2") state1 = server1.state state1.trame__title = ...
Python
1
import math import random import pandas as pd import numpy as np from sklearn.naive_bayes import GaussianNB from xgboost import XGBClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, matthews_corrcoef, f1_score, roc_curve, auc, \ precision_recall_curve from sklearn.preprocessing i...
Python
1
data payload is an uncompressed 8-bit alpha mask. Mask8, /// Icon element data payload is an RLE-compressed 24-bit RGB image. RLE24, /// Icon element data payload is a JPEG 2000 or PNG file. JP2PNG, } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; const ALL_ICON_TYPES: ...
Rust
0
from ...enum_types import _enum_logic_operators from ...sockets import NodeSocketLogicCondition from ...sockets import NodeSocketLogicVectorXYZ from ...sockets import NodeSocketLogicFloat from ...sockets import NodeSocketLogicFloatPositive from ..node import LogicNodeConditionType from ..node import node_type from bpy....
Python
1
er count = receveur["roses_count"][nom_envoyeur] texte = f"{nom_envoyeur} a envoyé {count} rose" + ("s" if count > 1 else "") + f" à {receveur['nom']}" if text_id is None: text_id = canvas.create_text( fenetre_width // 2, 50, text=texte, font=("Arial", 20, "bold"...
Python
1
name.map(|name| name.0.to_owned().into()), info, ) })); } } } extern crate libc; use libc::c_void; use thiserror::Error; #[derive(Debug, Error)] pub enum MemoryError { #[error("Out of range : {0:x}")] OutOfRange(usize), } #[derive(Clone, Copy)] ...
Rust
0
2`" )] pub struct MissingWriteAccessToTheDownloadBinary; #[derive(Debug, UserFacingError, Serialize)] #[user_facing(code = "P1008", message = "Operations timed out after `${time}`")] pub struct DatabaseOperationTimeout { /// Operation time in s or ms (if <1000ms) pub time: String, } #[derive(Debug, UserFacing...
Rust
0
clone())?) }) .map_err(|e| anyhow::anyhow!("{}", e))?; } let task_info = task_info.clone(); let peer_ids: Vec<String> = get_delegates_res .delegates .iter() .map(|v| v.peer_id.clone()) .c...
Rust
0
nombre = 'Raul' #Contexto Global idioma = 'Aleman' #Contexto Global def saludo(nombreFuncion,idioma):#Contexto Local # nombre = 'Xochitl' print(nombreFuncion) print(f"Buen dia en {idioma}" ) # print(nombre) # print("Buen dia") print("=====================") saludo(nombre,idioma) saludo(nombre,...
Python
1
from Py4GWCoreLib.enums import outpost_name_to_id, explorable_name_to_id # 1) IDs _6_championsdawn_to_jokanurdiggingsoutpost_ids = { "outpost_id": 479, } # 2) Outpost exit path _6_championsdawn_to_jokanurdiggingsoutpost_outpost_path = [ (24333, 8390), (24222, 7388), (23573, 6560), (22957, 5772), ]...
Python
1
Depends(v2_get_current_user) ): return await appeal_service.upload_team_statement(appeal_id, files, current_user) @router.post("/{appeal_id}/upload-merchant-statement") async def upload_merchant_statement( appeal_id: str, files: UploadFile, current_user: User = Depends(get_current_user_by_x_token_or_b...
Python
1
do this in 4-bit chunks to prevent overflow let num_chunks = (grid_depth + 3) / 4; Self { storage: DynamicStorage2D { bits: (0..num_chunks) .map(|chunk_index| { // Same weird calculation as with StaticStorage2D, see lengthy comment...
Rust
0
proto.edge) == g.number_of_edges() # Check the root node. assert proto.node[0].text == "root" @decorators.loop_for(seconds=10) def test_fuzz_NetworkXGraphToProgramGraphProto(): """Fuzz the networkx -> proto conversion using randomly generated graphs.""" g = random_cdfg_generator.FastCreateRandom() proto = n...
Python
1
4, } impl HSetting { pub fn new(setting_type: HSettingType, value: u64) -> Self { HSetting { setting_type, value, } } } #[derive(Clone, Debug, Default, PartialEq)] pub struct HSettings { settings: Vec<HSetting>, } impl HSettings { pub fn new(settings: &[HSettin...
Rust
0
kenize_data() # def tokenize_data(self): # tokenizer = self.spacy_tokenizer.en_tokenizer # def __tokenize_data(data): # for i in range(len(data["X"])): # data["X"][i] = [token.text.strip().lower() for token in tokenizer(data["X"][i].strip()) if token.text.strip()] # ...
Python
1
CallbackQuery.edit_message_media( media=med, reply_markup=InlineKeyboardMarkup(buttons) ) __MODULE__ = "Plᴀʏ" __HELP__ = """ <b>★ ᴘʟᴀʏ , ᴠᴘʟᴀʏ , ᴄᴘʟᴀʏ</b> - Aᴠᴀɪʟᴀʙʟᴇ Cᴏᴍᴍᴀɴᴅs <b>★ ᴘʟᴀʏғᴏʀᴄᴇ , ᴠᴘʟᴀʏғᴏʀᴄᴇ , ᴄᴘʟᴀʏғᴏʀᴄᴇ</b> - FᴏʀᴄᴇPʟᴀʏ Cᴏᴍᴍᴀɴᴅs <b>✦ c sᴛᴀɴᴅs ғᴏʀ ᴄʜᴀɴɴᴇʟ ᴘʟᴀʏ.</b> <b>✦ v sᴛᴀɴᴅs ғᴏʀ ...
Python
1
Plan::ShowRoles => write!(f, "ShowRoles"), Plan::CreateRole(_) => write!(f, "CreateRole"), Plan::DropRole(_) => write!(f, "DropRole"), Plan::ShowStages => write!(f, "ShowStages"), Plan::ListStage(_) => write!(f, "ListStage"), Plan::DescribeStage(_...
Rust
0
from __future__ import annotations from datetime import datetime import narwhals as nw from tests.utils import Constructor, assert_equal_data def test_filter(constructor: Constructor) -> None: data = { "time": [ "2021-01-01", "2021-01-02", "2021-01-03", "2...
Python
1
twork: Network, seed: &[u8], path: &[ChildNumber], expected_sk: &str, expected_pk: &str) { let mut sk = ExtendedPrivKey::new_master(network, seed).unwrap(); let mut pk = ExtendedPubKey::from_private(&sk); // Derive keys, checking hardened and non-...
Rust
0
ut it's highly unlikely there's a directory called that, # so we'll assume it's because the parent dir is not writable. # This could as well be because the parent dir is not readable, # due to non-privileged user access. return False else: os.close(fd)...
Python
1
<Msb0, u8> = BitVec::new(); // for el in vec_hash { // let bit_0 = el.get(&'0').unwrap_or(&0); // let bit_1 = el.get(&'1').unwrap_or(&0); // if bit_0 > bit_1 { // res_bv.push(false) // } else { // res_bv.push(true) // } // } // let res_bv_com...
Rust
0
#! /usr/bin/env python3 from sys import argv from re import search from math import log, floor assert len(argv) == 4, f"Usage: {argv[0]} <min> <max> <regex>" min, max, regex = argv[1], argv[2], argv[3] assert len(regex) <= 80, "regex too large" padding = floor(log(int(max) + 1, 10)) + 1 for i in range(int(min), ...
Python
1
ints_slices_f[:] = ints_slices[:,col,row] ints_slices = None if cd_low_tag == 'eig': cderi_block = cupy.dot(cd_low.T, ints_slices_f) ints_slices = None elif cd_low_tag == 'cd': cderi_block = solve_triangular(cd_low, ints_slic...
Python
1
(-torch.log(torch.tensor(0.7)) - torch.log(torch.tensor(0.8))).item() / 2), ]) def test_compute_nll(predictions, targets, expected_nll): """ The function `test_compute_nll` is a unit test that checks if the computed negative log-likelihood (NLL) matches the expected NLL within a small margin of error. ...
Python
1
/// | 'nan' /// ; fn take_special_float(i: &str) -> IonResult<&str, f64> { alt(( value(INFINITY, tag("+inf")), value(NEG_INFINITY, tag("-inf")), value(NAN, tag("nan")), ))(i) } enum FloatOrDecimal { Float(String), Decimal(String), } fn take_float_or_decimal(i: &str) -> ...
Rust
0
oice} => _process_add_bet(program_id, accounts, choice), Instruction::SetWinner{result} => _process_set_winner(program_id, accounts, result), Instruction::Withdraw => _process_withdraw(program_id, accounts), } } // Sanity tests #[cfg(test)] mod test { use super::*; use solana_program::clock...
Rust
0
ED_IN_SYSTEM_CONTAINER: ::DWORD = 8615; pub const ERROR_DS_LDAP_SEND_QUEUE_FULL: ::DWORD = 8616; pub const ERROR_DS_DRA_OUT_SCHEDULE_WINDOW: ::DWORD = 8617; pub const ERROR_DS_POLICY_NOT_KNOWN: ::DWORD = 8618; pub const ERROR_NO_SITE_SETTINGS_OBJECT: ::DWORD = 8619; pub const ERROR_NO_SECRETS: ::DWORD = 8620; pub const...
Rust
0
recursive function traverses shadow DOMs function getActiveElement(root) { const active_element = root.activeElement; if (!active_element) { return null; } if (active_element.shadowRoot) { return getActiveElement(active_element.shadowRoot); } else { ...
Python
1
one)] pub enum Gender { Male, Female, } impl Save { pub fn read<R: Read + Seek>(mut reader: R) -> LoadSaveResult<Self> { // Check both slots and pick the most recent one let sector_results = ( Sector::read_at(&mut reader, 0), Sector::read_at(&mut reader, SAVE_SECTION...
Rust
0
"""Melody playback functionality for Murnau synthesizer""" import math import time from pythonosc import udp_client def midi_to_freq(midi_note): """Convert MIDI note number to frequency Args: midi_note (int): MIDI note number (0-127) Returns: float: Frequency in Hz """ return 4...
Python
1
_, _, _, _, color) => *color, }, } } fn hovered(&self) -> button::Style { let active = self.active(); button::Style { shadow_offset: active.shadow_offset + Vector::new(0.0, 1.0), background: Some(Background::Color(Color:...
Rust
0
ROW '→': 0xc7, # RIGHTWARDS ARROW '←': 0xc8, # LEFTWARDS ARROW '┌': 0xc9, # BOX DRAWINGS LIGHT DOWN AND RIGHT '┐': 0xca, # BOX DRAWINGS LIGHT DOWN AND LEFT '└': 0xcb, # BOX DRAWINGS LIGHT UP AND RIGHT '┘': 0xcc, # BOX DRAWINGS LIGHT UP AND LEFT '●': 0...
Python
1
total_deleted = 0 try: conn = sqlite3.connect(db_path) cursor = conn.cursor() for table_name, days_to_keep in self.db_cleanup_rules.items(): cutoff_date = datetime.now() - timedelta(days=days_to_keep) ...
Python
1
, "cpp", "cxx", "c++") and CXX not in custom_languages: custom_languages.append(CXX) elif arg in ("gcc", "g++") and GCC not in custom_compilers: custom_compilers.append(GCC) elif arg in ("clang", "clang++") and CLANG not in custom_compilers: custom_compilers.append(CLANG) elif ...
Python
1
e twice, one deep and one shallow hash. This allows to differentiate /// queries which depend on the full HIR tree and those which only depend on the item signature. fn hash_owner( &mut self, node: hir::OwnerNode<'hir>, bodies: &SortedMap<hir::ItemLocalId, &'hir hir::Body<'hir>>, ) ...
Rust
0
use lazy_static::lazy_static; use std::collections::HashMap; lazy_static! { pub(super) static ref TO_OP_CODE_OPERAND_KIND_HASH: HashMap<&'static str, OpCodeOperandKind> = { // GENERATOR-BEGIN: OpCodeOperandKindHash // ⚠️This was generated by GENERATOR!🦹‍♂️ let mut h = HashMap::with_capacity(109); let _ = h.i...
Rust
0
import unittest from api import * class TestTheRosaryAPI(unittest.TestCase): def test_get_today_prayer(self): response = get_today_prayer() self.assertIsInstance(response, list) def test_get_yesterday_prayer(self): response = get_yesterday_prayer() self.assertIsInstance(respon...
Python
1
IGH']: pkl_path = os.path.join(self.model_dir, "sklearn_pipeline_standalone.pkl") # Save model with open(pkl_path, 'wb') as f: pickle.dump(self.pipeline, f) def reload_from_standalone(self, **kwargs) -> None: '''Reloads a model from its configuration and ...
Python
1
ributes"] pub tcd3_attr: crate::Reg<tcd3_attr::TCD3_ATTR_SPEC>, _reserved_68_dma_tcd3_nbytes: [u8; 0x04], #[doc = "0x106c - TCD Last Source Address Adjustment"] pub tcd3_slast: crate::Reg<tcd3_slast::TCD3_SLAST_SPEC>, #[doc = "0x1070 - TCD Destination Address"] pub tcd3_daddr: crate::Reg<tcd3_da...
Rust
0
de(rename = "cache.r5.2xlarge")] CacheR52xlarge, #[serde(rename = "cache.r5.4xlarge")] CacheR54xlarge, } /// AWS ElastiCache parameters for infrastructure provisioning /// /// Simplified input for configuring a single instance Redis for your service. /// Based loosely on the inputs from: /// - [aws elastic...
Rust
0
n, k = map(int, input().split(' ')) # 동전의 종류를 동전의 개수 n만큼 입력 받음 coin_list = [] for _ in range(n): coin_list.append(int(input())) coin_list.sort(reverse=True) cnt = 0 for coin in coin_list: if k / coin >= 1: cash_cnt = k // coin k -= coin * cash_cnt cnt += cash_cnt print(cnt)
Python
1
ProposalPayload { new_entries }; assert!( forward_call_via_universal_canister( &fake_governance_canister, &registry, "update_node_rewards_table", Encode!(&payload).unwrap(), ) .await ); let tabl...
Rust
0
= optim_embeds + positional_encoding batched_attn_mask = torch.ones(1, num_prompt_tokens, device=model.device) input_embeds = torch.cat([before_embeds, optim_embeds_with_pe, after_embeds, target_embeds], dim=1) input_attn_mask = torch.cat([left_attn_mask, batched_attn_mask, right_at...
Python
1
{ bytes.push(cx.expr_u8(expr.span, byte)); } } // u8 literal, push to vector expression ast::LitUint(v, ast::TyU8) => { if v > 0xFF { cx.span_err(expr.span, "too large u8 literal in ...
Rust
0
# This software is licensed under a dual license: # # 1. Creative Commons Attribution-NonCommercial (CC BY-NC) # for individuals and open source projects. # 2. Commercial License for business use. # # For commercial inquiries, contact: license@tradiny.com # # For more details, refer to the LICENSE.md file in the roo...
Python
1
_env().await; let dynamodb_local_config = get_dynamodb_config(&profile, &config); let s3_local_config = get_s3_config(&profile, config); let dynamodb = aws_sdk_dynamodb::Client::from_conf(dynamodb_local_config); let s3 = aws_sdk_s3::Client::from_conf(s3_local_config); let dish_loader = DishLoader::n...
Rust
0
import setuptools long_description = ''' Texar is an open-source toolkit based on Tensorflow, aiming to support a broad set of machine learning especially text generation tasks, such as machine translation, dialog, summarization, content manipulation, language modeling, and so on. Texar is designed for both research...
Python
1
error); read_write!(lvt_timer); read_write!(lvt_thermal); read_write!(lvt_perf); read_write!(lvt_lint0); read_write!(lvt_lint1); read_write!(lvt_error); read_write!(ticr); read!(tccr); read_write!(tdcr); write!(self_ipi); } bitflags! { /// Error flags in the APIC error statu...
Rust
0
n mol.GetAtoms() if atom.GetAtomicNum() == 6 and not atom.IsInRing()] if not acyclic_carbon_indices: return False, "No acyclic carbon atoms found" acyclic_carbon_set = set(acyclic_carbon_indices) # Build a dictionary mapping each acyclic carbon index to its neighboring acyclic carbons. carbon_gr...
Python
1
MemoType; use mc_util_telemetry::{ block_span_builder, mark_span_as_active, telemetry_static_key, tracer, Context, Key, Span, SpanKind, Tracer, }; use mc_util_uri::ConsensusClientUri; use more_asserts::assert_gt; use once_cell::sync::OnceCell; use serde::Serialize; use std::{ sync::{ atomic::{Atomic...
Rust
0
# Atividade 08: # Média de Notas: # Desenvolva um programa que solicite as notas dos alunos até # que o usuário digite -1. Calcule e exiba a média das notas # inseridas. cont = 0 soma = 0 n1 = float(input("Enter the note: ")) while n1 cont += 1 soma += n1 if n1 == -1: break print(f'Note: {n1}')
Python
1
""" The missing harbor python SDK See: https://github.com/vmware/harbor/tree/master/contrib/sdk/harbor-py """ from setuptools import setup, find_packages from codecs import open from os import path setup( name='harbor-py', # Versions should comply with PEP440. For a discussion on single-sourcing # the ...
Python
1
put_order".to_string())), AnnExpr::Expr(Expr::VarParIdentifier("indomain_min".to_string())), AnnExpr::Expr(Expr::VarParIdentifier("complete".to_string())) ] }] } )) ); } //! FLoating point power utilities. use c...
Rust
0
SDLEvent::MultiGesture { d_dist, .. } => { let mouse_state = self.event_pump.mouse_state(); let center = Vector2I::new(mouse_state.x(), mouse_state.y()); Some(Event::Zoom(d_dist, center)) } _ => None, } } fn convert_sdl...
Rust
0
# Copyright (c) 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights ...
Python
1
if self.consumer_client: self.consumer_client.unsubscribe() yield Either( right=OMetaTopicSampleData( topic=topic_entity, sample_data=TopicSampleData(messages=sample_data), ) ) def decode_message(sel...
Python
1
_of::<Header>(), 128); } } #![no_std] #![allow(warnings)] //! Typic helps you transmute fearlessly. It worries about the subtleties of //! ***[soundness]*** and ***[safety]*** so you don't have to! //! //! Just import it and replace your `#[repr(...)]` attributes with `#[typic::repr(...)]`: //! ``` //! // Import i...
Rust
0
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from fairseq import utils from fairseq.modules import ( LayerNorm, ...
Python
1
version.minor = version.minor - 1; } else if version.major > 0 { version.major = version.major - 1; } let mut version_string = String::new(); version_string.push_str(&version.major.to_string()); version_string.push_str("."); version_string.push_str(&version.minor.to_string()); ...
Rust
0
he rigid body. let rb = RigidBodyDesc::new() .translation(Vector3::new(x, y, z)) .build(); let rb_handle = world.bodies.insert(rb); // Build the collider. let co = ColliderDesc::new(cuboid.clone()) ...
Rust
0
te({'tar_ext': tar_ext, 'tar_ixt': tar_ixt}) if self.split != 'train': ret.update({'tar_img': tar_img, 'tar_dpt': tar_dpt, 'tar_mask': tar_mask}) ret.update({'near_far': np.array(self.depth_ranges).astype(np.float32)}) ...
Python
1