text string | label_name string | labels int64 |
|---|---|---|
from item import Item
from inventory import Inventory
from vending_machine import VendingMachine
coke = Item('Coke', 0.5, 2, 1, 10)
pepsi = Item('Pepsi', 0.5, 2, 2, 10)
sprite = Item('Sprite', 0.5, 2, 3, 10)
lays = Item('Lays', 1, 3, 4, 10)
doritos = Item('Doritos', 1, 3, 5, 10)
fritos = Item('Fritos', 1, 3, 6, 10)
tw... | Python | 1 |
gs.url,
param=args.param,
method=args.method,
threads=args.threads,
timeout=args.timeout,
proxies=proxies,
user_agents=args.user_agents,
output=args.output,
selected_tests=selected_tests,
post_data=post_data,
db=args.db,
tbl=args.tb... | Python | 1 |
unsafe {
cursor
.read_exact(slice::from_raw_parts_mut(
code.as_mut_ptr() as *mut u8,
words * 4,
))
.expect("bad read");
code.set_len(words);
}
// check magic number
let magic_number =... | Rust | 0 |
use holochain_serialized_bytes::prelude::*;
#[derive(Clone, PartialEq, Serialize, Deserialize, SerializedBytes, Debug)]
pub enum PostCommitCallbackResult {
Success,
Fail(HeaderHashes, String),
}
impl From<ExternIO> for PostCommitCallbackResult {
fn from(guest_output: ExternIO) -> Self {
match gues... | Rust | 0 |
const="DEBUG",
default="SUCCESS",
)
args = parser.parse_args()
log_setup(args.loglevel)
seq_lens, stoichiometries, query_seqs, unpairedmsas, pairedmsas = (
get_info_from_json(args.input)
)
write_a3m_file(
args.out,
seq_lens,
query_seqs,
stoi... | Python | 1 |
to_cmd {
($input:expr, ($pkg:expr, $yes:expr), $cmd:expr) => {{
let subcommand = SubCommand::from_str($input).unwrap();
assert_eq!(subcommand.to_cmd($pkg, $yes), Some($cmd.to_string()));
}};
($input:expr, ($pkg:expr, $yes:expr)) => {{
let subcommand = SubComma... | Rust | 0 |
2_Foundation", feature = "Win32_UI_WindowsAndMessaging"))]
pub fn GetPointerTouchInfo(pointerid: u32, touchinfo: *mut POINTER_TOUCH_INFO) -> super::super::super::Foundation::BOOL;
#[doc = "*Required features: `\"Win32_UI_Input_Pointer\"`, `\"Win32_Foundation\"`, `\"Win32_UI_WindowsAndMessaging\"`*"]
#[cfg(a... | Rust | 0 |
e","attribution":{"contributor":{"resource":"A-1"},"modified":1394175600000},"qualifiers":[{"name":"http://gedcomx.org/RectangleRegion","value":"rectangle region value"}]}],"analysis":{"resource":"http://identifier/for/analysis/document"},"notes":[{"lang":"en","subject":"subject","text":"This is a note","attribution":{... | Rust | 0 |
FadeToDark(300, 0, 100)
Sound(17, 0, 100, 0)
SetChrName("")
AnonymousTalk(
0x3E7,
(
scpstr(0x1F, 0xE3),
scpstr(0x7, 0x0),
"を手に入れた。\x02",
)
)
CloseMessageWindow()
OP_57(0x0)
FadeToBright(300, 0)
OP_3F(0xE3, 0x1)
OP_5B(0xE... | Python | 1 |
#!/usr/bin/env python2
import numpy as np
# right hand convention
def RotMatX(deg):
rad = np.deg2rad(deg)
s, c = np.sin(rad), np.cos(rad)
Rx = np.eye(3)
Rx[1, 1] = c
Rx[2, 2] = c
Rx[1, 2] = -s
Rx[2, 1] = s
return Rx
def RotMatY(deg):
rad = np.deg2rad(deg)
s, c = np.sin(ra... | Python | 1 |
"""
Deprecated module - do not use.
Used to contain private type aliases. These are now in the `polars._typing` module.
"""
from typing import Any
import polars._typing as plt
from polars._utils.deprecation import issue_deprecation_warning
def __getattr__(name: str) -> Any:
if name in dir(plt):
issue_d... | Python | 1 |
from .utils import create_model, to_sdl
__all__ = ['create_model', 'to_sdl']
| Python | 1 |
cx.tcx.def_kind(item.def_id).descr(item.def_id.to_def_id());
span_lint_and_then(
cx,
REDUNDANT_PUB_CRATE,
span,
&format!("pub(crate) {} inside private module", descr),
|diag| {
di... | Rust | 0 |
Dynamic,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for PrivateIpAllocationMethod {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> De... | Rust | 0 |
us': 441, 'tout': 446, 'toute': 462, 'toutes': 484, 'trois-quarts': 487, 'tu': 509, 'un': 150, 'une': 150, 'vos': 149, 'votre': 150, 'vous': 558, 'à': 563, 'ça': 135, '<morph>': {':M¬:G': 47}, '<lemmas>': {'autan': 69, 'soie': 73}, '<meta>': {'WORD': 62}}, 565: ['g2__purge_horaires_et_durée__b9_a1_1'], 566: {'<rules>':... | Python | 1 |
append(v);
}
SetData { def: *set_def, data }
}
/// Calculates the set defined by `set_def`.
fn calc_set(set_def: &SetDefinition) -> SetData {
let capacity = set_def.width_px * set_def.height_px * set_def.oversampling * set_def.oversampling;
let mut point_data: Vec<u32> = Vec::with_capacity(capacity as ... | Rust | 0 |
import requests, pickle
import json
import os
import re
import ast
import paramiko
import ipaddress
import jdatetime
import traceback
from pathlib import Path
from bs4 import BeautifulSoup
from selectolax.parser import HTMLParser
from datetime import datetime
from time import time, sleep
from uuid import uuid4
user_a... | Python | 1 |
metrize(
"value", [
{"MD5": "a"},
{"SHA-256": "2dfb1bcc980200c6706feee399d41b3f"},
],
)
def test_hashes_property_invalid(value):
hash_prop = HashesProperty(["sha256", "md5"])
with pytest.raises(ValueError):
hash_prop.clean(value, False)
def test_hashes_property_custom():
v... | Python | 1 |
ds, v);
out
}
/// a bit unsafe w.r.t. matching, but I don't know how to type this :(
pub fn iter_mut(&mut self) -> hash_map::IterMut<'_, String, (String, HashSet<DataSource>)> {
self.fields.iter_mut()
}
pub fn from_iterator<I: IntoIterator<Item = (String, DataSource, String)>>(
... | Rust | 0 |
2x4),
// gl::DOUBLE_MAT3x2 => Some(DMat3x2),
// gl::DOUBLE_MAT3x4 => Some(DMat3x4),
// gl::DOUBLE_MAT4x2 => Some(DMat4x2),
// gl::DOUBLE_MAT4x3 => Some(DMat4x3),
gl::SAMPLER_1D => Some(Sampler1D),
gl::SAMPLER_2D => Some(Sampler2D),
gl::... | Rust | 0 |
# Corrected code for test_zarr.ipynb
import xarray as xr
import numpy as np
# Cell 1: Create HM from band "AA" and drop "AA" from ds
HM = ds.sel(band="AA")
ds = ds.drop_sel(band="AA")
print("HM created:")
print(HM)
print("\nds after dropping AA:")
print(ds)
# Cell 2: Filter dsv to only include dates before 2021
# FI... | Python | 1 |
from __future__ import annotations
import asyncio
from enum import Enum
from typing import TYPE_CHECKING, Any, Callable
if TYPE_CHECKING:
from cassandra.cluster import ResponseFuture, Session
async def wrapped_response_future(
func: Callable[..., ResponseFuture], *args: Any, **kwargs: Any
) -> Any:
"""W... | Python | 1 |
missing", subcommand)));
};
set_namespace(
format!("/tmp/vagga/namespaces/net.{}", ip), Namespace::Net)
.map_err(|e| Err(format!("Can't set namespace: {}", e)))?;
let mut cmd = Command::new(&command);
cmd.args(&cmdargs);
match cmd.status() {
Ok(status) if status.success() =... | Rust | 0 |
page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, "boolxai", "BoolXAI Documentation", [author], 1)]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source... | Python | 1 |
)
.unwrap(),
"a {\
\n b: rgba(0, 0, 255, 0.5);\
\n}\
\n"
);
}
#[test]
fn transparent() {
assert_eq!(
rsass(
"a {b: rgb(rgba(0, 0, 255, 0.3), 0)}\
\n"
... | Rust | 0 |
y<'entries> for directory::simple::Simple<'entries> {
fn add_node<Entry>(
&mut self,
name: &str,
entry: Entry,
moniker: &AbsoluteMoniker,
) -> Result<(), ModelError>
where
Entry: DirectoryEntry + 'entries,
{
self.add_entry(name, entry).map_err(|_| ModelErr... | Rust | 0 |
verfitting)")
st.write("And for the training set we have: ",mae2)
st.write("The Mean Absolute Error is 1 719 868, we have almost the same than our test set so our model is well train (no overfitting)")
#To predict the number of followers for a specific popularity rate(e.g. 90)
popularity_to_predict = 90
predicted_fol... | Python | 1 |
unsafe {
ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_event_queue_destroy, self.wlevq);
}
}
}
<reponame>greg904/costau
use itertools::Itertools;
use num_rational::BigRational;
use num_traits::{One, Pow, Signed, ToPrimitive, Zero};
use std::collections::hash_map::DefaultHasher;
use std::colle... | Rust | 0 |
!
//! See the [original announcement on Reddit](https://www.reddit.com/r/rust/comments/b59zt9/first_crate_movie_an_actor_library/).
//!
//! ## Docs
//!
//! README.md is built using [`cargo-readme`] (`cargo readme > README.md`). The documentation
//! is built by [`docs.sh`] script.
//!
//! ## License
//!
//! Copyright 2... | Rust | 0 |
8388608;
pub const USB_OTG_GNPTXSTS_NPTXQTOP_Pos: u32 = 24;
pub const USB_OTG_GNPTXSTS_NPTXQTOP_Msk: u32 = 2130706432;
pub const USB_OTG_GNPTXSTS_NPTXQTOP: u32 = 2130706432;
pub const USB_OTG_GNPTXSTS_NPTXQTOP_0: u32 = 16777216;
pub const USB_OTG_GNPTXSTS_NPTXQTOP_1: u32 = 33554432;
pub const USB_OTG_GNPTXSTS_NPTXQTOP... | Rust | 0 |
::AllocInfo {
crate::TEST_MONITOR.local_info()
}
pub fn after_alloc<T>(obj: T, before: interloc::AllocInfo) {
mem::drop(obj);
let diff = crate::TEST_MONITOR.local_info().relative_to(&before);
assert!(
diff.bytes_alloc == diff.bytes_dealloc,
"Diff is {:#?}",
diff
);
}
#![feat... | Rust | 0 |
elf.internet_gateway_id {
::serde::ser::SerializeMap::serialize_entry(&mut map, "InternetGatewayId", internet_gateway_id)?;
}
::serde::ser::SerializeMap::serialize_entry(&mut map, "VpcId", &self.vpc_id)?;
if let Some(ref vpn_gateway_id) = self.vpn_gateway_id {
::serde::se... | Rust | 0 |
from System import *
from Rhino import *
from Rhino.DocObjects import *
from Rhino.Geometry import *
from Rhino.Input import *
from Rhino.Input.Custom import *
from Rhino.Commands import *
from scriptcontext import doc
def RunCommand():
filter = ObjectType.Surface | ObjectType.PolysrfFilter | ObjectType.Mesh
rc, o... | Python | 1 |
"""Conway's Game Of Life, Author Anurag Kumar(mailto:anuragkumarak95@gmail.com)
Requirements:
- numpy
- random
- time
- matplotlib
Python:
- 3.5
Usage:
- $python3 game_o_life <canvas_size:int>
Game-Of-Life Rules:
1.
Any live cell with fewer than two live neighbours
dies, as if caused by under-popu... | Python | 1 |
記号 SQUARE_MEETORU
pub const WIDE_JIS_SYMBOL_SQUARE_MEETORU: u32 = 0x334d;
/// 全角 JIS 記号 SQUARE_RITTORU
pub const WIDE_JIS_SYMBOL_SQUARE_RITTORU: u32 = 0x3351;
/// 全角 JIS 記号 SQUARE_WATTO
pub const WIDE_JIS_SYMBOL_SQUARE_WATTO: u32 = 0x3357;
/// 全角 JIS 記号 SQUARE_ERA_NAME_HEISEI
pub const WIDE_JIS_SYMBOL_SQUARE_ER... | Rust | 0 |
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_community.llms import Ollama
import streamlit as st
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Streamlit config
st.set_page_config(page_title=" Chat... | Python | 1 |
from datetime import timedelta
MAX_CONTINUOUS_DRIVE = timedelta(hours=4.5)
BREAK_TIME = timedelta(minutes=45)
MAX_DAILY_DRIVE = timedelta(hours=9)
OVERNIGHT_REST = timedelta(hours=11)
def plan_driver_schedule(total_distance, speed):
"""
total_distance: км
speed: км/ч
"""
total_time_hours = total_d... | Python | 1 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score
# Load the dataset
file_path = 'path_to_your_data/data1_Ch4_Real estate.cs... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# __doc__.py Document in reST format of tui module.
#
# Copyleft (C) 2014 - huhamhire <me@huhamhire.com>
# =====================================================================
# Licensed under the GNU General Public License, version 3. You should
# have received a copy ... | Python | 1 |
import time
import os
import json
import random
import webbrowser
import requests
from colorama import init, Fore, Style
import keyboard
import re
# Inicializa colorama para que los colores funcionen en la consola.
init()
# --- Variables del Juego ---
SAVE_FILE = "terminalcoin_save.json"
wallet = 0.0
mining_speed = 0... | Python | 1 |
number.and_then(|c| Some(if c == 0 { 1 } else { c })).unwrap_or(1);
match model {
Mode::TOKIO => {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(thread_num)
.enable_all()
.build()
.unwrap()
.block_on(a... | Rust | 0 |
"demo"}]})
await hass.async_block_till_done()
config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
CONF_ENTITY_ID: "switch.decorative_lights",
CONF_INVERT: True,
CONF_TARGET_DOMAIN: Platform.COVER,
},
title="Title is ignore... | Python | 1 |
(usize, usize)) -> Vec<Vec<char>> {
let mut out = vec![vec![' '; width]; height];
for (pos, tile) in board {
out[pos.1][pos.0] = match tile {
Tile::Floor => '.',
Tile::Wall => '#',
};
}
out
}
fn print_units_onto_board(printed_board: &mut Vec<Vec<char>>, units: &Vec<Unit>) {
for unit in... | Rust | 0 |
zero(),
ImageRendering::Auto,
AlphaType::PremultipliedAlpha,
image_info.key,
ColorF::WHITE);
},
_ => { },
}
// TODO: determine if image has overflown its container
None
}
#[inline]
fn push_border(
info: &Pr... | Rust | 0 |
yload_mut(&mut self) -> &mut [u8] {
&mut self.payload
}
}
impl io::rx::Entry for Packet {
type Handle = Tuple;
fn read(
&mut self,
_local_address: &LocalAddress,
) -> Option<(datagram::Header<Self::Handle>, &mut [u8])> {
let header = datagram::Header {
path:... | Rust | 0 |
DEFAULT_NEGATIVE_PROMPT = """
low quality, worst quality, normal quality, text, signature, jpeg artifacts,
bad anatomy, old, early, mini skirt, nsfw, chibi, multiple girls, multiple boys,
multiple tails, multiple views, copyright name, watermark, artist name, signature
"""
DEFAULT_FORMAT = {
"tag only (DTG mode)... | Python | 1 |
, "({})", e)?;
}
if min == 0 && max == 1 {
write!(f, "?")?;
} else if min == 0 && max == 0 {
write!(f, "*")?;
} else if min == 1 && max == 0 {
write!(f, "+")?;
} else if min == max... | Rust | 0 |
import pandas as pd
from .base import ArcsBase
from .fetch import FetchParix
from coolbox.utilities.bed import process_pairs
from coolbox.utilities.genome import GenomeRange
class Pairs(ArcsBase, FetchParix):
"""
Arcs track from .pairs file.
Parameters
----------
file: str
Path of .pairs... | Python | 1 |
import os
import requests
from datetime import date, datetime
from supabase import create_client
from dotenv import load_dotenv
# Cargar variables de entorno
load_dotenv()
API_KEY = os.getenv("CURRENCY_API_KEY")
SUPABASE_URL = os.getenv("supabaseURL")
SUPABASE_KEY = os.getenv("supabaseKEY")
# URL de la API de tasas ... | Python | 1 |
# L1 American English Dialects from https://catalog.ldc.upenn.edu/LDC93S1
import os
import sys
import zipfile
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from data_loaders.common import BaseDataset, interactive_flag_samples
from core.audio import audio_bytes_to_array
from core.codes import parse_... | Python | 1 |
from duckduckgo_search import DDGS
def search_duckduckgo(query):
with DDGS() as ddgs:
return list(ddgs.text(query, max_results=5)) | Python | 1 |
1b659","dps":{"1":true,"2":0}}"#
.as_bytes()
.to_owned();
let parser = MessageParser::create("3.1", None).unwrap();
let message_to_encode = Message::new(&payload, CommandType::DpQuery, None);
let encoded = parser.encode(&message_to_encode, false).unwrap();
assert!(parser.parse(&encoded... | Rust | 0 |
bail!(IllegalState(format!("index before sequence")));
}
if self.ef_index >= self.num_encoded {
bail!(IllegalState(format!("index after sequence")));
}
Ok(self.ef_index)
}
pub fn current_value(&self) -> i64 {
self.combine_high_low_values(self.current_hig... | Rust | 0 |
();
let mut ddtags = BTreeMap::new();
ddtags.insert("env".to_owned(), "staging".to_owned());
let hostname = hostname::get().unwrap();
let time = SystemTime::now();
let stream_event = StreamEvent {
aggregation_key: None,
alert_type: Some(Error),
... | Rust | 0 |
import pandas as pd
from config import iot23_experiments_dir
from src.helpers.file_helper import find_files_recursively
from src.helpers.fix_test_data_for_roc import add_missing_class_rows_to_test_data
from src.iot23 import get_exp_data_dir, get_train_data_path, get_test_data_path
def fix_test_data_to_plot_roc_curve... | Python | 1 |
into the pulse generator counter as its top value.
Waveform,
}
/// Selects up mode or up-and-down mode for the counter
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum CounterMode {
/// Up counter (edge-aligned PWM duty cycle)
Up,
/// Up and down counter (center-aligned PWM duty cycle)
UpAndDo... | Rust | 0 |
"""
Core API Routes
This module handles basic functionality routes including models, scenes, and health checks.
Extracted from the monolithic app/api/v1/router.py as part of Phase 2 refactoring.
"""
from fastapi import APIRouter, Response, HTTPException, Query
from starlette.responses import FileResponse
from typing ... | Python | 1 |
import os
from datetime import timedelta
import pendulum
from airflow import DAG
from airflow.providers.postgres.operators.postgres import PostgresOperator
from airflow.sensors.external_task import ExternalTaskSensor
from macros import get_table_name
with DAG('devices_aggregator', max_active_runs=1,
default... | Python | 1 |
}
}
impl<'s> InputTakeAtPosition for Fragment<'s> {
type Item = char;
fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.source().find(predicate) {
Some(i) => Ok(self.take_split(i)),... | Rust | 0 |
model (LLM).
"""
Retrieval = AdaRetrieval
LLM = AutoModelDecoderRAGLLMV2
def __str__(self):
return super().__str__() + "-MPTLLMAdaRetrieverFSRAG"
class MPTLLMBERTRetrieverFSRAG(FewShotRAG):
"""
FewShotRAG model with BERT retrieval and AutoModelDecoderRAGLLMV2 as the language model (LLM... | Python | 1 |
rotate: 0.0,
center_x: -1.5,
center_y: 0.0
},
color_offset: 0.0,
palette: 1.0,
palette_scale: 1.0,
outer_scale: 1.0,
blend_mode: 0.0,
alpha_offset: 1.0,
lock_mode: false,
loc... | Rust | 0 |
"""
Crea un diccionario donde las claves sean
el conjunto 1 de la siguiente tabla y los
valores, el conjunto 2:
conjunto 1:
e i k m p q r s t u v
p v i u m t e r k q s
El programa debe pedir una frase al usuario y
debe mostrar la frase encriptada. Para ello, cada
vez que encuentre en la frase una letra del conjun... | Python | 1 |
edToday,
Prechecked,
ReportRequestedSuccess,
ReportRequestedFailed,
Success,
Failed,
}
trait UpdateStage {
fn update(&mut self, target: PipelineStage);
}
impl UpdateStage for PipelineStage {
fn update(&mut self, target: PipelineStage) {
if *self < target {
*self = target;
}
}
}
pub stru... | Rust | 0 |
of a leap year
end_leap_year_offset_range: (i64, i64),
}
/// Julian day in `[1, 365]`, without taking occasional February 29th into account, which is not referenceable
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Julian1WithoutLeap(u16);
impl Julian1WithoutLeap {
/// Construct a transition rule da... | Rust | 0 |
mute_gt_images).item())
if args.compute_lpips:
LPIPS_list.append(lpips(permute_images,permute_gt_images, net_type='vgg').item())
with open(os.path.join(path_test_results,"metrics.txt"),"w") as f:
f.write("Mean PSNR SSIM LPIPS\n")
mean_PSNR=sum(PSNR_list)/len(PSNR_list)
m... | Python | 1 |
# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/SequenceNetworkSync.py
import CGF
import logging
import BigWorld
from functools import partial
from Event import Event
from cgf_components_common.scenario.sequence_network_sync import SequenceNetworkSync as Sync
from script_componen... | Python | 1 |
/// string and a single SHA256 hash of protocol-specific tag:
/// `lnbp1_msg = SHA256("LNPBP1") || SHA256(<protocol-specific-tag>) || msg`
/// 2. Compute HMAC-SHA256 of the `lnbp1_msg` and `P`, named **tweaking
/// factor**: `f = HMAC_SHA256(s, P)`
/// 3. Make sure that the tweaking factor... | Rust | 0 |
trolEndpoint, endpoints: Vec<::usb_core::Endpoint>, descriptors: &[u8]) -> ::usb_core::device::Instance<'a> {
// 1. Find the HID descriptor in the list
// 2. Locate the report descriptor (0x22) and get the length
let mut report_desc_len = 0;
for d in ::usb_core::hw_decls::IterDescriptors(descriptors)
{
// ... | Rust | 0 |
from dataclasses import dataclass
from datetime import datetime
@dataclass
class PaymentApplied:
"""
Event triggered when a payment is successfully applied.
"""
payment_id: str
customer_id: str
total_amount: float
timestamp: datetime = datetime.now()
@dataclass
class PaymentRejected:
... | Python | 1 |
_args(args_str);
return true;
} else if args_str.contains(&(prefix.clone() + CHANGELOG)) {
message_printer::print_changelog();
return true;
} else if args_str.contains(&(prefix.clone() + SHOW_LANGUAGES)) {
message_printer::print_supported_languages(language_map);
return ... | Rust | 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 the License is distributed on an
// "AS IS" ... | Rust | 0 |
filter_map(Result::ok)
.filter_map(|i| i.parse::<i32>().ok())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::{fs::File, io::BufReader};
#[test]
fn part1_sample() {
let numbers = vec![1721, 979, 366, 299, 675, 1456];
assert_eq!(part1(numbers), 514579)
}... | Rust | 0 |
# -*- encoding:utf-8 -*-
"""
多支交易对象进行择时操作封装模块,内部通过AbuPickTimeWorker进行
择时,包装完善前后工作,包括多进程下的进度显示,错误处理捕获,结果
处理等事务
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import logging
import numpy as np
import pandas as pd
from enum import Enum
from ... | Python | 1 |
);
let (mut z2, mut z3) = constant_time_swap(z_2, z_3, swap);
swap = bit_val;
let mut tmp0 = x3 - z3;
let mut tmp1 = x2 - z2;
x2 = x2 + z2;
z2 = x3 + z3;
z3 = x2 * tmp0;
z2 = z2 * tmp1;
tmp0 = tmp1.sqr(1);
tmp1 = x2.sqr(1);
x3 = ... | Rust | 0 |
id }}</Id>
<Name>{{ zone.name }}</Name>
<ResourceRecordSetCount>{{ zone.rrsets|count }}</ResourceRecordSetCount>
</HostedZone>
</UpdateHostedZoneCommentResponse>
"""
ASSOCIATE_VPC_RESPONSE = """<?xml version="1.0" encoding="UTF-8"?>
<AssociateVPCWithHostedZoneResponse>
<ChangeInfo>
<Comment>{{ ... | Python | 1 |
dict = {"DRUG":"药品",
"DRUG_INGREDIENT":"药物成分",
"DISEASE":"疾病",
"SYMPTOM":"症状",
"SYNDROME":"证候",
"DISEASE_GROUP":"疾病分组",
"FOOD":"食物",
"FOOD_GROUP":"食物分组",
"PERSON_GROUP":"人群",
"... | Python | 1 |
rch.save(model.state_dict(), os.path.join(args.out_dir, f"model_{t}.pt"))
return results
def main(args):
mps_device = torch.device("mps")
wandb_name = f"{args.training.task}: depth {args.model.depth}, headcount {args.model.headcount}"
if 'samples' in args.training:
wandb_name += f", samples {... | Python | 1 |
import os
from langfuse import Langfuse
from datetime import datetime, timezone
# Langfuse 인스턴스 싱글턴 생성 (환경변수에서 키/호스트 자동 로드)
langfuse = Langfuse()
def log_inference_to_langfuse(
trace=None,
name="vllm-inference",
prompt=None,
messages=None,
text_prompt=None,
content=None,
model_name=None,
... | Python | 1 |
TahnnakiTemple = [
(2884.86, -12387.98),
(227.31, -7360.89),
(2259.09, -3369.35),
(3171.27, 2108.69),
(5448.64, 6261.96),
(7727.54, 7918.97),
(6018.50, 12309.87),
(2701.72, 15909.80),
(35.89, 15392.52),
(3262.73, 17048.24),
(-496.69, 18513.76),
(-5882.72, 18474.70),
(... | Python | 1 |
i_range=args.xi_range,
xi_n=args.xi_n,
alpha_range=args.alpha_range,
alpha_n=args.alpha_n,
sample_n=args.sample_n,
parallel=args.parallel,
)
# Define ranking and data
ranking = pd.Series([1, 2, 3, 4, 5])
data = pd.DataFrame(
{
"LocationID": [1... | Python | 1 |
rformance_best_model_inner = accuracy_score(y_test, model_inner_predict)
performance_results.append(performance_best_model_inner)
if performance_best_model_inner > best_performance:
best_performance = performance_best_model_inner
... | Python | 1 |
self
}
#[doc="Get the TVAL Register."]
#[inline] pub fn tval_reg(&self) -> ::bobbin_mcu::register::RegisterArray<Tval, ::bobbin_bits::R4> {
::bobbin_mcu::register::RegisterArray::new(self.0 as *mut Tval, 0x20, 0x10)
}
#[doc="Get the *mut pointer for the TVAL register."]
#[inli... | Rust | 0 |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or module... | Python | 1 |
196, 187, 153, 11, 61, 30, 18],
10 => [25, 51, 95, 152, 196, 198, 190, 156, 115, 64, 32, 20],
11 => [26, 54, 96, 150, 192, 200, 189, 157, 115, 66, 33, 21],
12 => [30, 58, 101, 165, 203, 220, 206, 173, 128, 74, 39, 24],
13 => [29, 57, 104, 164, 205, 220, 199, 167, 120, 68, 35, 22],
... | Rust | 0 |
" => "Telev.",
"temperature" => "Temp.",
"terrestrial" => "Terr.",
"theoretical" => "Theor.",
"transactions" => "Trans.",
"translation" => "Transl.",
"transmission" => "Transmiss.",
"transportation" => "Transp.",
"tutorials" => "Tut.",
"ultrasonic" => "Ultrason.",
"university" =>... | Rust | 0 |
<CTX> for I
where
I: Iterator,
I::Item: ConvWith<CTX>,
{
type Output = <I::Item as ConvWith<CTX>>::Output;
}
pub struct ConvWithIter<I, CTX> {
iter: I,
ctx: CTX,
}
impl<I, CTX> Iterator for ConvWithIter<I, CTX>
where
I: Iterator,
I::Item: ConvWith<CTX>,
CTX: Copy,
{
type Item = <I:... | Rust | 0 |
content written to it.
///
/// For example, `"_` in Vim.
Blackhole,
/// A register representing the windowing environment's most recently selected text.
///
/// For example, `"*` in Vim, or what clicking the mouse's middle button pastes in X and
/// Wayland.
SelectionPrimary,
/// ... | Rust | 0 |
"k", lw=3, alpha=0.2)
ax4.semilogx(u, XHeI, zorder=-1, color="k", lw=3, alpha=0.2)
ax4.semilogx(u, XHeII, zorder=-1, color="k", lw=3, alpha=0.2)
ax4.semilogx(u, XHeIII, zorder=-1, color="k", lw=3, alpha=0.2)
ax4.semilogx(u_theory, XHI_theory, label="expected HI", ls=":", **plotkwargs)
ax4.semilogx(u_theory, XHII_theor... | Python | 1 |
index_mask: u16 = 0b1000_0000_0000_0000;
let mut index: usize = 0;
loop {
if index >= 16 {
break;
}
if mask & index_mask != 0 {
spans.push(self.spans[index]);
}
index += 1;
... | Rust | 0 |
lculator.calculate_feature_importance(
self.X, self.y, method="random_forest"
)
# 檢查結果
self.assertEqual(len(importance), self.X.shape[1])
self.assertAlmostEqual(importance.sum(), 1.0, places=5) # 重要性總和為 1
# 檢查前 5 個重要特徵
top_features = importance.nlargest(5).... | Python | 1 |
import hashlib
# Compat wrapper to always include the `usedforsecurity=...` parameter,
# which is only added from Python 3.9 onwards.
# We use this flag to indicate that we use `md5` hashes only for non-security
# cases (our ETag checksums).
# If we don't indicate that we're using MD5 for non-security related reasons,... | Python | 1 |
# This program pre-sells a limited number of cinema tickets.
# Each buyer may buy up to 4 tickets &
# No more than 20 total tickets may be sold.
# Prompts user for desired num of tickets and
# displays remaining num of tickets.
# Repeats til all tickets are sold
# then displays total num of buyers.
TICKETS = 20 ... | Python | 1 |
e of A = B; C = D | E; F(x_) = G;");
///
/// let r = parse_rule(&mut sig, "C = D").expect("parse of C = D");
///
/// assert_eq!(t.remove_clauses(&r).expect("removing C = D").display(), "C = D");
///
/// assert_eq!(t.display(),
/// "A = B;
/// C = E;
/// F(x_) = G;");
/// ```
... | Rust | 0 |
from enum import Enum
class ModuleType(str, Enum):
"""Module type enumeration."""
Magnetic = "magdeck"
Temperature = "tempdeck"
Thermocycler = "thermocycler"
Heatershaker = "heatershaker"
| Python | 1 |
h pytest.raises(NotImplementedError):
MyPartialListener().update_service(
zc, "_tivo-videostream._tcp.local.", "Tivo1._tivo-videostream._tcp.local."
)
zc.close()
def test_signal_registration_interface():
"""Test adding and removing from the SignalRegistrationInterface."""
int... | Python | 1 |
#[test]
#[should_panic]
fn test_for_offset() {
panic!("Implementation specific: parsing API");
}
#[test]
#[should_panic]
fn test_for_body() {
panic!("Implementation specific: parsing API");
}
#[test]
#[should_panic]
fn test_tablerow_in() {
panic!("Implementation specific: parsing API");
}
#[test]
#[sho... | Rust | 0 |
8], tag: &[u8], message: &[u8]) -> Result<Vec<u8>> {
init_panic_hook();
let share: Share<PrivateKey> = bincode::deserialize(share_buf).map_err(|err| {
JsValue::from_str(&format!("could not deserialize private key share: {}", err))
})?;
let result = Poprf::partial_eval(&share, tag, message).map... | Rust | 0 |
AME>", &Location::new(53.761389, -7.2875)),
Customer::new(15, "<NAME>", &Location::new(53.1489345, -6.8422408)),
Customer::new(16, "<NAME>", &Location::new(53.0033946, -6.3877505))
]);
let expected_customers = CustomerList::from_vec(vec![
Customer::new(1, "<NAME>", &... | Rust | 0 |
.repository_dir)?;
let lockfile = &opt.lockfile;
if opt.update_lockfile {
if let Some(lockfile) = lockfile.as_ref() {
renderer
.render_lockfile(lockfile)
.context("Failed to update lockfile")?;
}
}
Ok(())
}
<filename>sui_core/src/gateway_sta... | Rust | 0 |
:
# Проверяем наличие ключа 'itemName'
item_name = stat.get('itemName', 'Не указано') # Или любое значение по умолчанию
if not item_name:
print("itemName отсутствует в:", stat) # Логируем элементы без itemName
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.