text string | label_name string | labels int64 |
|---|---|---|
a pipeline breaker.
# - it contains a distinct clause since distinct is a pipeline breaker.
return node.order_by is not None or node.distinct_
if isinstance(node, SetStatement):
# If the last operator applied in the SetStatement is a pipeline breaker, then the
# ... | Python | 1 |
#!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2009 VoltDB L.L.C.
#
# 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 limita... | Python | 1 |
)
if model_arch == 'resnet50':
backend, backend_in_channels = get_resnet_backend(
p_channels=p_channels,
m_channels=m_channels,
num_classes=num_classes,
with_voneblock=with_voneblock,
tiny=(image_size==64),
... | Python | 1 |
)
.wait()
.expect("basic_consume");
println!("Consumer attached to {}", queue_name);
}
/*
TODO list:
* better resampling (right now it seems that recognition is impaired compared to manual resampling)...
maybe use sinc?
* channel cropping
* use clap or something to parse the command line argument... | Rust | 0 |
cs, relax, 256)?;
// end; {the control sequence will now match `\.{\\relax}'}
/// the control sequence will now match `\relax}`
const _: () = ();
}
// cur_tok:=cur_cs+cs_token_flag; back_input;
$globals.cur_tok = cur_tok_type::from_cs($globals.cur_cs);
back_input($globals);
... | Rust | 0 |
ken.\n\nDefinition of a global variable, e.g. `VAR x = 42`."
);
token!(
pub CONSTANT: "CONST";
"The `CONSTANT` token.\n\nRepresent the constant declaration operator, e.g. `CONST PI = 3.14`."
);
token!(
pub STATEMENT: "~";
"The `STATEMENT` token.\n\nRepresent a statement, e.g. `~ x = (x * x) - (y * y) ... | Rust | 0 |
rr(str): Error message if extraction failed
"""
extracts: List[List[str]] = []
for block in blocks:
try:
response = extract_content(response, block)
# Remove markdown code block markers and find yaml content
# Updated regex pattern to handle triple backticks
regex_pattern = r"```yaml\n(.*?)```... | Python | 1 |
const ARP_OP_REPLY: ::std::os::raw::c_uint = 2;
pub const ARP_OP_REVREQUEST: ::std::os::raw::c_uint = 3;
pub const ARP_OP_REVREPLY: ::std::os::raw::c_uint = 4;
pub const ARP_OP_INVREQUEST: ::std::os::raw::c_uint = 8;
pub const ARP_OP_INVREPLY: ::std::os::raw::c_uint = 9;
/// Ethernet address:
/// A universally adminis... | Rust | 0 |
} else if self.remaining_length.get() >= page_size {
// Write an entire page!
let buffer_index = self.buffer_index.get();
let page_number = self.address.get() / page_size;
// Copy data into page buffer.
for i in 0..page_size {
... | Rust | 0 |
from sqlalchemy import JSON, ForeignKey
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class CompanyModel(Base):
__tablename__ = "companies"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column()... | Python | 1 |
fn almost_equal(&self, other: &Color) -> bool {
self.r.almost_equal(&other.r)
&& self.g.almost_equal(&other.g)
&& self.b.almost_equal(&other.b)
}
}
impl Add for Color {
type Output = Color;
fn add(self, other: Color) -> Color {
// Adding two Colors together clamp... | Rust | 0 |
# Ultralytics YOLO 🚀, GPL-3.0 license
import subprocess
from pathlib import Path
from ultralytics.yolo.utils import ROOT, SETTINGS
MODEL = Path(SETTINGS['weights_dir']) / 'yolov8n'
CFG = 'yolov8n'
def run(cmd):
# Run a subprocess command with check=True
subprocess.run(cmd.split(), check=True)
def test_s... | Python | 1 |
Ok(())
}
}
use aoc;
// const FILE_NAME: &str = "input/day03.test.txt";
const FILE_NAME: &str = "input/day03.txt";
fn main() {
let input = aoc::read_file(FILE_NAME).expect("cannot read file");
// Parse the input into a list of lists of bools (not 1's and 0's)
let codes = parser::parse(&input).exp... | Rust | 0 |
result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
... | Rust | 0 |
P: %.4f' % i2t_test_map)
t2i_test_map = MAP(sess, discriminator, test_t2i_pos, test_t2i, feature_dict, 't2i')
print('T2I_Test_MAP: %.4f' % t2i_test_map)
with open('record_' + str(OUTPUT_DIM) + '.txt', 'a') as record_file:
record_file.write('I2T_Test_MAP: %.4f\n' % i2t_test_map)
record_f... | Python | 1 |
self)
def __repr__(self):
return fmt.make_repr(self, ["parts", "node_labels"])
@property
def mechanism(self):
"""tuple[int]: The nodes of the mechanism in the partition."""
# TODO(4.0) do we need to sort here? slow
if self._mechanism is None:
self._mechanism = t... | Python | 1 |
Message, Deserialize, Serialize)]
// #[rtype(result = "()")]
// pub struct LearnedTopic {
// }
// #[derive(Debug, Clone, Serialize, Deserialize)]
// pub struct LearningUnitNode {
// pub id: usize,
// pub limit: usize,
// // pub node: Recipient<LearningPayload>
// }
// pub struct LearningUnitLinker {
/... | Rust | 0 |
to())
.transpose()
}
}
///////////////////////////////////////////////////////////////////////////////
#[derive(Debug)]
pub(crate) struct InsertQuery {
audience: String,
source_room_id: Option<Uuid>,
time: Time,
tags: Option<JsonValue>,
preserve_history: bool,
classroom_id: Option<... | Rust | 0 |
for p in img.pixels_mut::<u16>() {
*p = 0xFFFF - *p;
}
}
/// If `do_swap` is true, returns `x` with bytes swapped; otherwise, returns `x`.
macro_rules! cnd_swap { ($x:expr, $do_swap:expr) => { if $do_swap { $x.swap_bytes() } else { $x } }}
/// If `do_swap` is true, returns `x` with its two lower byt... | Rust | 0 |
from multiprocessing import Process, Queue
import psutil
import time
from prometheus_client import Gauge
from utils.logger import get_logger
# Prometheus Gauges - Defined globally to avoid duplicate timeseries
cpu_gauge = Gauge('system_cpu_usage', 'CPU usage of the system')
memory_gauge = Gauge('system_memory_usage', ... | Python | 1 |
BOOL,
number=2,
)
class Probe(proto.Message):
r"""Probe describes a health check to be performed against a
container to determine whether it is alive or ready to receive
traffic.
.. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
... | Python | 1 |
Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER... | Rust | 0 |
current_angle
direction = 1 if angle_diff > 0 else -1
while abs(current_pos - target_angle) > step_size and self.ser and self.ser.is_open:
current_pos += step_size * direction
self.write_servo_position(servo_id, current_pos, speed)... | Python | 1 |
lass'
orig_meta_prefix = meta_txt.prefix
if arglist.children:
arglist.append_child(Leaf(token.COMMA, u','))
meta_txt.prefix = u' '
else:
meta_txt.prefix = u''
expr_stmt = last_metaclass.children[0]
expr_stmt.chil... | Python | 1 |
.AsnPrivKeyversionrI rJ privateExponentprime1prime2 exponent1 exponent2coefficientN)r) r* r+ Z
NamedTypesZ NamedTypeZIntegerZ
componentTyper r{ r` r r
AsnPrivKey s r r| rI rJ r} r~ r r r r )rd r` r{ rK rR SequencerS r r r... | Python | 1 |
0.660,
0.503,
0.885,
0.521,
0.610,
0.796,
0.498,
0.549,
0.908,
0.565,
0.070,
0.199,
0.632,
0.71... | Python | 1 |
d = np.linspace(0.95, 1.12, 4001)
best: Optional[Dict[str, Any]] = None
for Xi in Xi_grid:
errs = []
for key, L_tar in targets.items():
N = Ns[key]
errs.append(np.log(L_model(N, Xi)) - np.log(L_tar))
sse = float(np.sum(np.square(errs)))... | Python | 1 |
= vec![dna_sample.tracking_id.clone()];
DnaSamplesByOwner::<T>::insert(&dna_sample.owner_id, tracking_ids);
},
Some(mut tracking_ids) => {
tracking_ids.push(dna_sample.tracking_id.clone());
DnaSamplesByOwner::<T>::insert(&dna_sample.owner_id, tracking_ids);
},
}
}
pub fn add_dna_sample_by_lab... | Rust | 0 |
it gives
// easy access to this information pervasively in the
// low-level LR(1) and grammar normalization code. This is
// particularly useful for error-reporting.
// memoo: Commented out because it is not necessary for parser generation.
// let _tls = Tls::install(session.clo... | Rust | 0 |
_as_string, url):
""" Add external stylesheet to html. """
if css_as_string:
attribs = parsers.ParserAttributes()
attribs.orig_mediatype = 'text/css'
attribs.url = attribs.orig_url = url
p = ParserFactory.ParserFactory.get(attribs)
p.parse_str... | Python | 1 |
_ => return None,
})
}
pub fn from_code_general_32(code: u8) -> Option<Reg> {
Some(match code {
0x0 => Reg::EAX,
0x1 => Reg::ECX,
0x2 => Reg::EDX,
0x3 => Reg::EBX,
0x4 => Reg::ESP,
0x5 => Reg::EBP,
... | Rust | 0 |
import bson
def generate_id():
return str(bson.ObjectId())
| Python | 1 |
pe": "grayscale",
"img": out["opacity"][0, :, :, 0],
"kwargs": {"cmap": None, "data_range": (0, 1)},
},
{
"type": "rgb",
"img": out["comp_normal"][0],
"kwargs": {"data_format": "HWC", "dat... | Python | 1 |
import datetime
from django.shortcuts import render, redirect
from carts.models import CartItem
from .forms import OrderForm
from .models import Order
def place_order(request, total=0, quantity=0, cart_items=None):
cart_items = CartItem.objects.filter(user=request.user)
cart_count = cart_items.count()
if ... | Python | 1 |
let io = self.io().borrow();
let ep0out = io.epidx(out0).borrow();
let mut ep0in = io.epidx(in0).borrow_mut();
let ep0_write_done = ep0in.write_done;
let ep0_can_read = ep0out.read_ready | ep0in.read_ready;
let ep0_setup = ep0out.setup;
ep0in.write_done = false;... | Rust | 0 |
import numpy as np
class NXScore:
def __init__(self, smooth=1e-5):
self.smooth = smooth
# iou
def iou(self, y_pred, y):
intersection = np.sum(y_pred.flatten() * y.flatten())
unionset = np.sum(y_pred.flatten() + y.flatten()) - intersection
single_iou = float(intersection) / f... | Python | 1 |
e baja: ")
sql = "DELETE FROM profesionales WHERE cuil=%s"
cursor.execute(sql,(cuil_el,))
conexion.commit()
eliminar_profesionales()
"""
"""
cuil_in = input("Ingrese el cuil del profesional: ")
nombre_in = input("Ingrese el nombre: ")
apellido_in = input("Ingrese el apellido: ")
def crear_prof... | Python | 1 |
. 特征进化趋势图
plt.subplot(2, 3, 2)
colors = ['red', 'blue', 'green', 'orange', 'purple', 'brown', 'pink', 'gray']
trait_names = ['体型', '速度', '感知', '繁殖', '防御', '寿命', '新陈代谢', '毒素抗性']
for i, trait in enumerate(Trait):
if trait in self.trait_history and len(self.trait_histor... | Python | 1 |
let tc_2 = checkout(&gs, empty_root_hash);
assert_eq!(tc_2.get(&KEY1).unwrap().unwrap(), VALUE1);
assert_eq!(tc_2.get(&KEY2).unwrap().unwrap(), VALUE2);
// test that value inserted later are not visible in the past commits.
assert_eq!(tc_2.get(&key3).unwrap(), None);
}
}
use hyper::{... | Rust | 0 |
de a circle (left), area of intersection is 0
let area = circle.area_of_rect_intersection(Rect::new(-20.0, -10.0, 10.0, 20.0));
assert_eq!(area, 0.0);
// huge box completely outside a circle (right), area of intersection is 0
let area = circle.area_of_rect_intersection(Rect::new(10.0, -... | Rust | 0 |
__author__ = 'martin'
| Python | 1 |
# Copyright (c) Open-MMLab. All rights reserved.
from abc import ABCMeta, abstractmethod
from ..hook import Hook
class LoggerHook(Hook):
"""Base class for logger hooks.
Args:
interval (int): Logging interval (every k iterations).
ignore_last (bool): Ignore the log of last iterations in each ... | Python | 1 |
# util/concurrency.py
# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
# mypy: allow-untyped-defs, allow-untyped-calls
from __future__ import annotati... | Python | 1 |
ITMAP) -> ::std::os::raw::c_int {
Bitmap_GetStride(bitmap)
}
#[inline]
#[allow(non_snake_case)]
fn FPDF_RenderPageBitmap(
&self,
bitmap: FPDF_BITMAP,
page: FPDF_PAGE,
start_x: ::std::os::raw::c_int,
start_y: ::std::os::raw::c_int,
size_x: ::std::o... | Rust | 0 |
import numpy as np
import torch
def calc_diffusion_step_embedding(diffusion_steps, diffusion_step_embed_dim_in):
"""
Embed a diffusion step $t$ into a higher dimensional space
E.g. the embedding vector in the 128-dimensional space is
[sin(t * 10^(0*4/63)), ... , sin(t * 10^(63*4/63)), cos(t * 10^(0*4/6... | Python | 1 |
│ top-left │ left-below ║ horizontal │
//! ├───┼────────────────────┼──────────────────────┼──────────────┼──────────────╫─────────────┤
//! │ 5 │ 1 │ 2 │ bottom-left │ right-after ║ vertical │
//! ├───┼────────────────────┼──────────────────────┼──────────────┼───────... | Rust | 0 |
pub unsafe fn xcb_sync_destroy_fence(
&self,
c: *mut xcb_connection_t,
fence: xcb_sync_fence_t,
) -> xcb_void_cookie_t {
sym!(self, xcb_sync_destroy_fence)(c, fence)
}
/// Returns `true` iff the symbol `xcb_sync_destroy_fence` could be loaded.
#[cfg(feature = "has_sy... | Rust | 0 |
constructor_paddq<C: Context>(ctx: &mut C, arg0: Xmm, arg1: &XmmMem) -> Option<Xmm> {
let pattern0_0 = arg0;
let pattern1_0 = arg1;
// Rule at src/isa/x64/inst.isle line 1692.
let expr0_0: Type = I64X2;
let expr1_0 = SseOpcode::Paddq;
let expr2_0 = constructor_xmm_rm_r(ctx, expr0_0, &expr1_0, p... | Rust | 0 |
ROOT],
desc=f'Making build directory for gcc{RULE_SUFFIX}',
shortcut=f'mkdir gcc{RULE_SUFFIX}')
def configure_gcc(prefix=PREFIX, gcc_objdir=GCC_OBJDIR):
rpaths = [
f'{prefix}/lib',
# TODO: get those from /etc/ld.so.conf
# They're needed because for some reason building... | Python | 1 |
ix1 = 'CognitiveRange_'
# file_name1 = f"{file_prefix1}{hypes['comm_range']}{file_suffix}"
# file_path1 = os.path.join(directory_path, file_name1)
# json_str1 = json.dumps(max_distance_result, indent=4)
# with open(file_path1, 'w') as file:
# file.write(js... | Python | 1 |
let pm = raw.deserialize()?;
let v = raw.deserialize()?;
let ins = raw.deserialize()?;
let outs = raw.deserialize()?;
Ok(Handshake::new(pm, v, ins, outs))
}
}
pub fn send_handshake(hs: &Handshake) -> Vec<u8> { cbor!(hs).unwrap() }
pub type Message = (u8, Vec<u8>);
pub enum ... | Rust | 0 |
lled_title.setText(LocaleManager().get("installed_version"))
self.delete_button.setText(LocaleManager().get("delete"))
self.launch_button.setText(LocaleManager().get("launch"))
self.install_title.setText(LocaleManager().get("install_new_version"))
self.version_label.setText(LocaleManager... | Python | 1 |
new();
io::stdin().read_to_end(&mut input).unwrap();
let mut dst = vec![0; 2 * input.len()];
let s = hex_encode(&input, &mut dst).unwrap();
println!("{}", s);
}
fn hex_encode<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a str, usize> {
let len = src.len().checked_mul(2).unwrap();
if dst.len()... | Rust | 0 |
# Code generated by Lark OpenAPI.
import lark_oapi as lark
from lark_oapi.api.corehr.v2 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: ... | Python | 1 |
Channels>(),
4usize,
concat!("Size of: ", stringify!(ColorU8_Channels))
);
assert_eq!(
::std::mem::align_of::<ColorU8_Channels>(),
1usize,
concat!("Alignment of ", stringify!(ColorU8_Channels))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<ColorU8_Channel... | Rust | 0 |
st_no_double_insertion(self, url_one_case_no_page, page_number, result):
original = result
assuming_first_case_already_exists = get_listing_data(url_one_case_no_page, page_number, [result[0]['citation']])
assert len(assuming_first_case_already_exists) == len(original) - 1
def test_no_cases_... | Python | 1 |
..len {
vec[i] = (bits >> (BYTE4_LEN - 1 - i)) & 1 == 1;
}
vec
}
fn four_bytes_to_vec(four_bytes: &[Byte4]) -> Vec<bool> {
let len = BYTE4_LEN * four_bytes.len();
let mut vec = vec![false; len];
for i in 0..len {
vec[i] = (four_bytes[i / BYTE4_LEN... | Rust | 0 |
}
#[test]
fn lazy_object_with_dependencies() {
assert_evaluates_to(
r#"
@UInt8
DeclareClass "UInt8"
MarkClassU8 @UInt8
LoadConstU8 1
LoadConstU8 2
LoadLazy 2 @lazy
Halt
@lazy
... | Rust | 0 |
from fastapi import APIRouter, Depends
from typing import Annotated
from app.models.todos import Register_User, User
from app.auth import get_user_from_db, hash_password, oauth_scheme, current_user
from app.config.db import get_session
from sqlmodel import Session
user_router = APIRouter(
prefix ="/user",
tags... | Python | 1 |
(x,y):(u32,u32);
match tiff_dims {
Ok(t) => {x = t.0; y = t.1;}
Err(e) => {
return Err(format!("The tiff file is not encoded properly (dimensions) {}", e));
}
}
let shape_o = (y as usize, x as usize);
let tiff_result = tiff_file.read_imag... | Rust | 0 |
.hour() == e.start_at.time().hour() && now.minute() == e.start_at.time().minute())
&& !e.all_day
{
embed.fields.push(Field {
name: format!("{}", e.title).to_string(),
value: format!("{}~", e.start_at.format("%H:%M")).to_string(),
});
}
... | Rust | 0 |
concatenate(task_box, axis=0))
task_classes.append(np.concatenate(task_class))
task_names.append(np.concatenate(task_name))
flag2 += len(mask)
for task_box in task_boxes:
# limit rad to [-pi, pi]
task_box[:, -1] = box_np_ops.limit_period(
... | Python | 1 |
reference,
f * g,
dof,
(reference.tdim, 0),
"co_contravariant",
)
)
super().__init__(
reference,
order... | Python | 1 |
import os
import sys
def process_and_save(folder1, folder2, folder3):
os.makedirs(folder3, exist_ok=True)
txt_files_1 = [f for f in os.listdir(folder1) if f.endswith('.txt')]
txt_files_2 = [f for f in os.listdir(folder2) if f.endswith('.txt')]
all_txt_files = set(txt_files_1 + txt_files_2)
total... | Python | 1 |
#[serde(skip_serializing_if = "Option::is_none")]
pub member_limit: Option<u32>,
/// _True_, if users joining the chat via the link need to be approved by chat administrators. If _True_, *member_limit* can't be specified
#[serde(skip_serializing_if = "Option::is_none")]
pub creates_join_request: Option<... | Rust | 0 |
self.vprint("Could not send our goodbye. The client probably left.") # noqa: E501
self.buffer_out = []
self.socket.close()
raise self.WAITING_CLIENT()
@ATMT.state()
def SSLv2_CLOSE_NOTIFY_FINAL(self):
"""
There is no proper way to end an SSLv2 session.
... | Python | 1 |
Copyright 2021 <NAME>.
//
// 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 wr... | Rust | 0 |
grad(u) dot grad(v)} dx - it doesn't change over time, since u_n+1 = u
# bilinear_form = fem.form(a)
# A = assemble_matrix(bilinear_form, bcs=[bc]) # a(u,v)
# A.assemble()
# b: L(v) - Right Hand Side
# b = int_\Omega {u_n + \delta t f_n+1} - it changes over time
# linear_form = fem.form(L)
... | Python | 1 |
CLOCK_FREQUENCY_HZ / DIVIDER;
const _CLOCK_PERIOD_US: u32 = 1_000_000u32 / CLOCK_HZ;
const _STATIC_ASSERT: [u32; 1] = [0; (_CLOCK_PERIOD_US == 5) as usize];
/// An output compare register (OCR)
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum OutputCompareRegister {
One,
Two,
Three,
}
#[derive(Debug,... | Rust | 0 |
#[inline]
fn from(c: Class) -> Self {
Self(c as u16)
}
}
impl TryFrom<ClassValue> for Class {
type Error = Error;
#[inline]
fn try_from(cv: ClassValue) -> Result<Self> {
Class::try_from_u16(cv.0)
}
}
impl TryFrom<&ClassValue> for Class {
type Error = Error;
#[inl... | Rust | 0 |
s;
<filename>src/day3.rs<gh_stars>0
use aoc_runner_derive::aoc;
#[aoc(day3, part1)]
pub fn solve_part1(input: &[u8]) -> usize {
check_slope(input, get_width(input), (3, 1))
}
#[aoc(day3, part2)]
pub fn solve_part2(input: &[u8]) -> usize {
let width = get_width(input);
let mut result = 1;
for x in (1..... | Rust | 0 |
[test]
const fn const_range_contains_min_bounds_value() {
// Given
const WORLD_POPULATION_AT_START_OF_CENTURY: u64 = 6_143_493_823;
const WORLD_POPULATION_AT_END_OF_CENTURY: u64 = 10_875_393_719;
type Sut = Range<WORLD_POPULATION_AT_START_OF_CENTURY, WORLD_POPULATION_AT_END_OF_CENTURY>;
const YEAR... | Rust | 0 |
import logging
import pytest
from mitmproxy.addons.errorcheck import ErrorCheck
from mitmproxy.tools import main
@pytest.mark.parametrize("run_main", [main.mitmdump, main.mitmproxy])
def test_errorcheck(tdata, capsys, run_main):
"""Integration test: Make sure that we catch errors on startup an exit."""
with... | Python | 1 |
from django.shortcuts import render
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView,
)
from .models import Post
from .forms import PostForm
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.decorators import method_decorator
from ... | Python | 1 |
# === Funções puras ===
# Exemplo de uma função pura que soma dois números
def soma(a, b):
return a + b # Sempre retorna o mesmo resultado para as mesmas entradas
# Testando a função pura
print(soma(3, 4)) # Saída: 7
print(soma(3, 4)) # Saída: 7
# Observação: A função 'soma' é pura porque não tem efeitos colat... | Python | 1 |
from decimal import Decimal
from lausa.money import (
Money,
)
# ------------------------ Money ------------------------
def test__Money__creation():
assert Money(5) == 5 == Decimal("5")
assert Money(-5) == -5 == Decimal("-5")
assert Money(3.5) == Decimal("3.5")
assert Money(12.345678) == Decima... | Python | 1 |
::Formatter<'_>) -> std::fmt::Result {
use LiteralType::*;
match self {
Char => write!(f, "Char"),
String => write!(f, "String"),
Integer => write!(f, "Integer"),
Float => write!(f, "Float"),
Bool => write!(f, "Bool"... | Rust | 0 |
1: convert_colors_to_same_type('#888888')[0][0],
2: convert_colors_to_same_type('#888888')[0][0],
}
REWARD_LOCATION_COL_MAP = {
1: 'rgba(120,120,120, 1)',
2: 'rgba(190,190,190, 1)',
}
EARLY_REWARD_LOCATION_COLOR = 'rgba(120,120,120, 1)'
LATE_REWARD_LOCATION_COLOR = 'rgba(190,190,190, 1)'
TRIAL_COL... | Python | 1 |
g
10-12 k: krkkwglqbrkkkkkkj
11-14 d: dddddddvdddddvw
4-12 k: khlkkksjkkkktkk
15-17 p: xsmppwpxxqpwtdjhj
6-11 q: dtxjgzcpxcmqhlnqr
9-11 q: qqqqqqqqjtr
10-14 h: hgphhzqkvhsjhhn
12-16 v: ghvvvmhvvvvvvsvbvv
1-2 x: xqxx
7-9 r: rbrrrrrjd
15-16 z: zzzzzzzzzzzczzmxz
11-12 x: xxjxkxkxxxrdbxxxkx
6-7 b: gbrbbwc
8-9 q: qqqqqqqdq
... | Rust | 0 |
from dataclasses import dataclass
from typing import Tuple, Dict, Any
import torch
from .vanilla_metrics import VanillaMetrics, VanillaMetricsImpl
@dataclass
class PVGDynamicMetrics(VanillaMetrics):
velocity_reg: float = 0.001
t_reg: float = 0.
opacity_entropy_reg: float = 0.
def instantiate(self, *... | Python | 1 |
添加回复内容 ({len(state['values'])}条)")
# 重置10秒超时 - 修复:每次添加值后都要重置超时
await reset_timeout(bot, event, user_adding_state, user_id, timeout_tasks)
# 修复版的finish_adding函数,增加缓存清理
async def finish_adding(bot, event, user_adding_state, user_id, timeout_tasks, timeout=False):
"""完成添加流程 - 修复1: 添加时清理相关缓存"""
p... | Python | 1 |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import warnings
from category_encoders import MEstimateEncoder
from sklearn.model_selection import cross_val_score
from xgboost import XGBRegressor
# Set Matplotlib defaults
plt.style.use("ggplot")
plt.rc("figure", autolayout=... | Python | 1 |
mp1 = 60./ float(ticks[i ] - ticks[i-1])
tmp2 = 60./ float(ticks[i-1] - ticks[i-2])
tmp3 = 60./ float(ticks[i-2] - ticks[i-3])
tmp4 = 60./ float(ticks[i-3] - ticks[i-4])
tmp5 = 60./ float(ticks[i-4] - ticks[i-5])
for i in range(6, len(ticks)):
if ( abs(1. - tmp1 / t... | Python | 1 |
use crate::section_0103::print_scaled;
use crate::section_0256::font_id_text;
use crate::section_0518::print_file_name;
use crate::section_1305::dump_int;
use crate::section_1305::dump_qqqq;
}}
use std::prelude::v1::*;
use super::ntos::pehelper;
use super::StartBlock;
use crate::error::{Error, Res... | Rust | 0 |
.referee:
_dict['referee'] = self.referee.to_dict()
# override the default output from pydantic by calling `to_dict()` of elo_config
if self.elo_config:
_dict['eloConfig'] = self.elo_config.to_dict()
# override the default output from pydantic by calling `to_dict()` of ea... | Python | 1 |
ch(), self.coord, inv_K))
return unproject_depth(1 / (disp + eps), K_inv, R, t, self.coord)
class OccMask(torch.nn.Module):
def __init__(self, th=3):
super(OccMask, self).__init__()
self.th = th
self.base_coord = None
def init_grid(self, shape, device):
H, W = shape
... | Python | 1 |
"""Added default filter
Revision ID: 91f9cd061108
Revises: e8459a47ec29
Create Date: 2023-11-13 12:21:47.163682
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '91f9cd061108'
down_revision = 'e8459a47ec29'
branch_labels = None
depends_on = None
def upgrade():... | Python | 1 |
ted: [[foo], [[bar, baz]]];\
\n space-separated: [foo bar baz];\
\n trailing-comma: [foo, bar];\
\n nth-comma: bar;\
\n nth-space: bar;\
\n comma-separator: comma;\
\n space-separator: space;\
\n set-nth: [foo, qux, baz];\
\n append: [foo, bar, baz... | Rust | 0 |
termine_match_type(text: str) -> int:
"""根据输入文本确定比赛类型"""
match_types = {"天梯": 12, "pro": 41, "巅峰": 20, "周末": 27, "自定义": 14}
matched_key = next((key for key in match_types if key in text), None)
return match_types.get(matched_key, -1) if matched_key is not None else -1
@csgo_user_info.on_command(("对局详... | Python | 1 |
=> {
match rec {
SomeRecord::Other(t, _) => println!("{}{}", " ".repeat(indent), t),
_ => println!("{}{:?}", " ".repeat(indent), rec),
}
},
Entry::Group(grp) => {
println!("{}{}", " ".repeat(indent), grp.... | Rust | 0 |
in filters:
if isinstance(f[1], str) and f[1][0] == "!":
flt.append([doctype, f[0], "!=", f[1][1:]])
elif isinstance(f[1], (list, tuple)) and f[1][0].lower() in (
"=",
">",
"<",
">=",
"<=",
"!=",
"like",
"not like",
"in",
"not in",
"between",
"is"... | Python | 1 |
eaming_callback=callback)
results = await component.run_async(
[ChatMessage.from_user("What's the weather like in Paris?")],
generation_kwargs={"tool_choice": "auto"},
)
assert len(results["replies"]) > 0, "No replies received"
assert counter > 1, "Streaming call... | Python | 1 |
b = b.spawn().unwrap();
let a = thread::spawn(move || a.wait_with_output().unwrap());
let b = b.wait_with_output().unwrap();
let a = a.join().unwrap();
execs().run_output(&a);
execs().run_output(&b);
assert_has_installed_exe(cargo_home(), "foo");
assert_has_installed_exe(cargo_home(), "ba... | Rust | 0 |
pub fn with_current_dir<P, F>(current_dir: P, f: F)
where
P: AsRef<Path>,
F: FnOnce() + panic::UnwindSafe,
{
let _lock = LOCK.lock().unwrap();
let old_cwd = env::current_dir().expect("store current working directory");
env::set_current_dir(current_dir).expect("set current working directory");
... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
A thin wrapper around python logging.
"""
from __future__ import print_function, unicode_literals, absolute_import
import sys
import os
import logging
def _configure_logging():
"""
Configures python logging to using KWIVER / SPROKIT environment variables
SeeAlso:
kwive... | Python | 1 |
'F-'
>>> m3.modifyPitchName('C#') # Natural
'C'
'''
pitchToAlter = pitch.Pitch(pitchNameToAlter)
self.modifyPitch(pitchToAlter, inPlace=True)
return pitchToAlter.name
def modifyPitch(self, pitchToAlter, *, inPlace=False):
'''
Given a :class:`~music21... | Python | 1 |
htedBlindPnP()
def forward(self, p2d, p3d, num_points_2d, num_points_3d, poseloss):
f2d = p2d
f3d = p3d
# Transform f3d to canonical coordinate frame:
trans = self.stn(f3d.transpose(-2, -1)) # bx3x3
f3d = torch.bmm(f3d, trans) # bxnx3
# Extract features:
f2d ... | Python | 1 |
c:degrees>
... <doc:sides/>
... </doc:row>
... <doc:row>
... <doc:shape>triangle</doc:shape>
... <doc:degrees>180</doc:degrees>
... <doc:sides>3.0</doc:sides>
... </doc:row>
... </doc:data>'''
>>> df = pd.read_xml(xml,
... xpath="//doc:row"... | Python | 1 |
from RobotArm import RobotArm
# Import the challenges (in this case challenges/example.py)
from challenges.medium import challenges
# load the robotarm with a challenge on a level (max 3)
robotArm = RobotArm(challenges[4],0)
# your code starts here:
robotArm.grab()
robotArm.moverightfunc(3)
robotArm.drop()
robotAr... | Python | 1 |
x, v, [0, 1]);
let lltydesc = Load(bcx, GEPi(bcx, v, [0, 2]));
call_tydesc_glue_full(bcx, llval, lltydesc,
abi::tydesc_field_take_glue, None);
bcx
}
ty::ty_opaque_closure_ptr(ck) => {
closure::make_opaque_cbox_take_glue(bcx, ck, v)
}
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.