text string | label_name string | labels int64 |
|---|---|---|
# Atividade 06:
# Soma de Números Positivos:
# Escreva um programa que solicite números ao usuário até
# que ele digite um número negativo, somando apenas os
# números positivos inseridos.
soma = 0
n = 1
while n >= 0:
n = int(input('Digite um numero: '))
if n >= 0:
soma = n + n
else:
print(f'A soma é {som... | Python | 1 |
_g = g[[i in [vt_type, "No-Trim"] for i in g['type']]]
for la, __g in _g.groupby("language"):
__g['vocab_size'] = (__g['vocab_size'] / 10**3).astype(int)
if task == 'qg':
__g[['METEOR', 'BERTScore']] = (__g[['METEOR', 'BERTScore']] * 100).round(1)
__g[la... | Python | 1 |
s"])[0].permute(1, 0, 2).float()
) # T, N, D
rgbs = torch.from_numpy(frames).permute(0, 3, 1, 2).float()
visibles = torch.logical_not(torch.from_numpy(converted["occluded"]))[
0
].permute(
1, 0
) # T, N
query_points = torch.from_numpy(converted[... | Python | 1 |
("bin/", $name, ".dll"),
$crate::open_library_raw!("garrysmod/bin/", $name, ".dll")
}
}
#[cfg(all(target_os = "linux", target_pointer_width = "64"))] {
$crate::__private__gmod_rs__try_chained_open! {
$crate::open_library_raw!("bin/linux64/", $name, ".so"),
$crate::open_library_raw!("bin/linux64/l... | Rust | 0 |
| (KNumber::UNN(value), &KTy2::I32)
| (KNumber::UNN(value), &KTy2::U8)
| (KNumber::UNN(value), &KTy2::U16)
| (KNumber::UNN(value), &KTy2::U32)
| (KNumber::UNN(value), &KTy2::C8)
| (KNumber::UNN(value), &KTy2::C16)
| (KNumber::UNN(value), &KTy2::C32) => CExpr::Int... | Rust | 0 |
import time
import numpy as np
from pathlib import Path
from dataclasses import dataclass
import numpy.typing as npt
from plyfile import PlyData
from viser import transforms as tf
@dataclass
class SplatData:
centers: npt.NDArray[np.floating]
rgbs: npt.NDArray[np.floating]
opacities: npt.NDArray[np.floatin... | Python | 1 |
opcode: Vec<u8>,
// We can use ExitReason with `with-codec` feature,
position: Result<u64, ExitReason>,
stack: Option<Stack>,
memory: Option<Memory>,
},
StepResult {
result: Result<(), Capture<ExitReason, Trap>>,
return_value: Vec<u8>,
},
SLoad {
address: H160,
index: H256,
value: H256,
},
SStor... | Rust | 0 |
:return: the DCT-II of the signal over the last 3 dimensions
"""
x1 = idct(X, norm=norm)
x2 = idct(x1.transpose(-1, -2), norm=norm)
x3 = idct(x2.transpose(-1, -3), norm=norm)
return x3.transpose(-1, -3).transpose(-1, -2)
class LinearDCT(nn.Linear):
"""Implement any DCT as a linear layer; in p... | Python | 1 |
d_id.detach().cpu().tolist()
y_true_id = y_true_id.detach().cpu().tolist()
if y_pred_probs is not None:
y_pred_probs = y_pred_probs.detach().cpu().tolist()
y_true = []
y_pred = []
y_probs = []
sid = 0
for tids, pids in zip(y_true_id, y_pred_id):
... | Python | 1 |
from http import HTTPStatus
from sanic import response, Blueprint
from sanic.request import Request
from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from wrolpi.api_utils import json_response
from wrolpi.common import logger, wrol_mode_check
from wrolpi.errors import InvalidOrderBy, Val... | Python | 1 |
rPool` was received.
vpcscEnabled: Immutable. If true, the worker pool is created with a VPC-SC
compatible configuration. Users should set to true if the worker pool
project is part of a secured VPC-SC perimeter.
workerConfig: Worker configuration for the `WorkerPool`.
"""
class StateValueValue... | Python | 1 |
err_proportion=err_proportion,
render_diag=render_diag)
return colours, mask
def extract_per_vertex_features(mesh, image, feature_f, diagonal_range=None):
image = image.copy()
image.landmarks['mesh_2d'] = mesh.with_dims([0, 1])
if diagonal_range is not None:
... | Python | 1 |
class employee:
def __init__(self, name, id):
self.name = name
self.id = id
def showdetails(self):
print(f"the employee with {self.id} is {self.name}")
class programmer(employee):
def showlang(self):
print("the language is python")
# class persons(programmer(employee)):xx
# ... | Python | 1 |
ayer initialize')
#self.init_layer = TransformerEncoderLayerVanilla(args=args, out_proj=h_dim)
print('NUM GRU SCHEMAS:' + str(num_gru_schemas))
print('NUM Attention SCHEMAS:' + str(num_attention_schemas))
print('SCHEMA SPECIFIC:' + str(self.schema_specific))
a... | Python | 1 |
PRIMARY KEY (crate_name, crate_version, version, kind)
);
CREATE TABLE result_extract_crate (
id INTEGER UNIQUE NOT NULL,
crate_name TEXT NOT NULL,
crate_version TEXT NOT NULL,
version ... | Rust | 0 |
(),
),
];
let test_model_result =
TestEnvironmentBuilder::new().set_components(components).build().await;
let lifecycle_controller =
LifecycleController::new(Arc::downgrade(&test_model_result.model), vec![].into());
let (lifecycle_proxy, lifecycle_r... | Rust | 0 |
ercentage = (current_rss / current_size) * 100 if current_size > 0 else 0
print(f"File: {current_file} ({current_permissions})")
print(f" Size: {current_size} kB")
print(f" RSS: {current_rss} kB")
print(f" Cache percentage: {percentage:.2f}%")
print()
... | Python | 1 |
import numpy as np
def pagerank(H, gamma, max_iter=500, tol=1e-13):
n = H.shape[0]
e = np.ones(n)
v = e / n
d = H @ e
u = (d == 0).astype(float)
dh = d + u * n
dh = 1.0 / dh
x = np.random.rand(n)
x = x / np.sum(x)
for it in range(1, max_iter + 1):
y = x * dh
y... | Python | 1 |
th = cr.text_extents(&self.content).width;
let text_height = cr.text_extents(&self.content).height;
// Potentially draw a frame around the label
let curr_pos = cr.get_current_point();
cr.set_line_width(line_width);
cr.rel_move_to(-text_width / 2.0 - left_gap, text_height / 2.0 +... | Rust | 0 |
btcusdt.precision.tick_size, 0.5);
assert_eq!(btcusdt.precision.lot_size, 1.0);
assert!(btcusdt.quantity_limit.is_none());
}
#[test_case(MarketType::InverseSwap)]
#[test_case(MarketType::LinearSwap)]
fn test_contract_values(market_type: MarketType) {
check_contract_values!(EXCHANGE_NAME, market_type);
}
<g... | Rust | 0 |
, node);
}
}
let next_estimate_score = next_score + estimate_cost(next);
visit_next.push(MinScored(next_estimate_score, next));
}
}
None
}
struct PathTracker<G>
where
G: GraphBase,
G::NodeId: Eq + Hash,
{
came_from: HashMap<G::NodeId, G:... | Rust | 0 |
from openhands.resolver.patching.apply import apply_diff
from openhands.resolver.patching.patch import parse_patch
def test_patch_whitespace_mismatch():
"""Test that the patch application succeeds even when whitespace doesn't match."""
# Original content has a line with spaces
original_content = """class ... | Python | 1 |
DisplaySleepAssertion");
// const kIOPMAssertionTypePreventSystemSleep : CFString = CFString::from_static_string("PreventSystemSleep");
// const K_IOPMASSERTION_LEVEL_OFF : IOPMAssertionLevel = 0;
const K_IOPMASSERTION_LEVEL_ON: IOPMAssertionLevel = 255;
extern "C" {
pub fn IOPMAssertionCreateWithName(
as... | Rust | 0 |
nt by 1
docs[right].leaf_id -= 1; // Moved right2left --> decrement by 1
docs.swap(left, right);
}
}
// Floyd Rivest algorithm to partition the median document by gains.
// Results in a modified document slice such that the median value is in its correct position, everything to the
// left has a g... | Rust | 0 |
import sys
from Pixelator import Pixelator
import PixelEffect
class EffectType:
plain_fill = "fill"
mushy_effect = "mushy"
lumen_center = "lumen-center"
lumen_side = "lumen-side"
colors_256_effect = "256-colors"
smoke_effect = "smoke"
def main(image_path, pixel_size, pixel_effect_name, output):... | Python | 1 |
s_layer, bidirectional=True), # 피질-해마 상호작용
Synapse(self.emotion_layer, self.memory_layer, bidirectional=True), # 감정-문맥 상호작용
]
for i in range(num_layers - 1):
self.synapses.append(Synapse(self.processing_layers[i], self.processing_layers[i + 1]))
self.synapses.append(Syn... | Python | 1 |
if cls[0] == 0: # Fake
fakes_correct.update(bool(eq[0]))
elif cls[0] == 1:
reals_correct.update(bool(eq[0]))
else:
print(f"Unknown class!")
if i % 10 == 0:
print(f'TEST\t[{i:03d}/{len(dataloader... | Python | 1 |
#
#
# Copyright (C) 2013 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | Python | 1 |
should_error = true;
expected_errno = cond.expected_errno;
break;
}
}
print!("Testing {}...", socket_fn.format(args));
num_performed += 1;
let fd;
match check_socket_call(args, *socket_fn, should_error, expected_errno) {
... | Rust | 0 |
llelizable (e.g. rayon).
pub fn deserialize_batch<F>(
rows: &[ByteRecord],
fields: &[Field],
projection: Option<&[usize]>,
line_number: usize,
deserialize_column: F,
) -> Result<Chunk<Box<dyn Array>>>
where
F: Fn(&[ByteRecord], usize, DataType, usize) -> Result<Box<dyn Array>>,
{
deserialize... | Rust | 0 |
terval')
if init_config.get('remote'):
get_remote_config(config)
else:
config['streams'] = []
for stream_t in init_config['source']:
tmp_stream_info = {'url':stream_t[0], 'acr_id':stream_t[1]}
if len(stream_t) == 3:
... | Python | 1 |
ustfmt::skip]
pub const EDGE_NODE_IDS: [[usize; Tri10::EDGE_NNODE]; Tri10::NEDGE] = [
[1, 0, 6, 3],
[2, 1, 7, 4],
[0, 2, 8, 5],
];
#[rustfmt::skip]
pub const NODE_REFERENCE_COORDS: [[f64; Tri10::GEO_NDIM]; Tri10::NNODE] = [
[0.0 , 0.0 ], // 0
[1.0 ... | Rust | 0 |
origin_pos: Position::from_pgn("c2"),
origin_piece: B_PAWN,
dest_pos: Position::from_pgn("b1"),
dest_piece: W_KNIGHT,
meta_info: BISHOP_PROMO_CAPTURE
};
orig_board.print_board();
make_move(&mut board, mv.clone());
board.print_b... | Rust | 0 |
re.compute_ntlbg_constraint_loss(
representative_features,
ntlbg_results['mu_q'],
ntlbg_results['sigma_q']
)
# 总损失
total_loss = loss + 0.1 * ntlbg_loss # 调整权重
outputs.update({
'loss... | Python | 1 |
# (C) Copyright IBM Corp. 2019, 2020, 2021, 2022.
# 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 app... | Python | 1 |
from opencompass.openicl.icl_prompt_template import PromptTemplate
from opencompass.openicl.icl_retriever import ZeroRetriever
from opencompass.openicl.icl_inferencer import PPLInferencer
from opencompass.openicl.icl_evaluator import AccEvaluator
from opencompass.datasets import HFDataset
ocnli_reader_cfg = dict(
... | Python | 1 |
: Transform) {
*self = *self + other;
}
}
/// Subtract the values of one transform from another
///
/// Note you probably want Mul to combine Transforms. Subtraction is only useful in less common use cases like interpolation
impl Sub<Transform> for Transform {
type Output = Transform;
fn sub(self,... | Rust | 0 |
from typing import List, Union
from pyrogram import filters
other_filters = filters.group & ~filters.via_bot & ~filters.forwarded
other_filters2 = (
filters.via_bot & ~filters.forwarded
)
def command(commands: Union[str, List[str]]):
return filters.command(commands, "")
| Python | 1 |
# src/paralisi/processing/segmentation/sign_map_generator.py
import numpy as np
from numpy.typing import NDArray
from scipy.ndimage import gaussian_filter
import torch
class SignMapGenerator:
"""Handles generation of visual field sign maps from phase maps."""
def generate_sign_map(self, phase_hor: NDArray, p... | Python | 1 |
/// ```
/// use rsa::{RSAPrivateKey, PrivateKeyPemEncoding};
/// use rand::rngs::OsRng;
///
/// let mut rng = OsRng;
/// let bits = 2048;
/// let private_key = RSAPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
///
/// let _ = private_key.to_pem_pkcs1();
/// ```
... | Rust | 0 |
, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
],
];
for items in 2..8 {
let mut a = XOR128::new();
let mt: MerkleTree<[u8; 16], XOR128> = MerkleTree::from_iter(
[1, 2, 3, 4, 5, 6, 7, 8]
.iter()
.map(|x| {
... | Rust | 0 |
def extrapolate(part_two=False):
with open('input.txt') as f:
lines = f.readlines()
total = 0
for line in lines:
values = [int(value.strip()) for value in line.split(' ')]
if part_two:
values = values[::-1]
total+= find_extrapolate(values)
if... | Python | 1 |
def SO3_to_quat(R):
"""
:param R: (N, 3, 3) or (3, 3) np
:return: (N, 4, ) or (4, ) np
"""
x = RotLib.from_matrix(R)
quat = x.as_quat()
return quat
| Python | 1 |
# Databricks notebook source
# MAGIC %run
# MAGIC /azure_project/connection_folder/Utility
# COMMAND ----------
df = spark.readStream.format("cloudFiles").option("cloudFiles.format",'csv')\
.option("cloudFiles.schemaLocation","/dbfs/Filestore/tables/schema/flight")\
.option("cloudFiles.schemaEvolutio... | Python | 1 |
/// If a value other than None, then will wake up.
pub interrupt_notification_ie_wake_up: Option<WakeUp>,
/// Stream support.
pub stream_support: bool,
}
impl Default for RequestedFeatures
{
#[inline(always)]
fn default() -> Self
{
Self
{
remote_memory_access: true,
atomic_operations_32_bits_wide... | Rust | 0 |
est).unwrap();
println!("grpc_unary(): response = {:?}", response);
}
stop_server(server);
}
#[test]
fn grpc_unary_async() {
let server = start_server();
for &(ref host, port) in server.bind_addrs() {
println!("listening on {}:{}", host, port);
let env = Arc::new(EnvBuilder::... | Rust | 0 |
4f56b512128, 0x12c78531c310437d, 0xecbb47cf9365df27, 0xc971c8c46604cc65, 0x9fad8855c3df0300, 0x79b0a231fc3492d6, 0x63b3e95b1faaab6c]),
Uint512::from_raw([0x59014a49cf4e604a, 0x22175e06b2dad17c, 0x54ccd50ce1e8e305, 0x76011e6687fb23b2, 0xda24d80456884dbd, 0x32044b8e1c047601, 0xfc42f70ec2bc6e9c, 0x2ab3ce9a58423567])
);... | Rust | 0 |
import unittest
from unittest import mock
import asyncio
class ProtocolsAbsTests(unittest.TestCase):
def test_base_protocol(self):
f = mock.Mock()
p = asyncio.BaseProtocol()
self.assertIsNone(p.connection_made(f))
self.assertIsNone(p.connection_lost(f))
self.assertIsNone(... | Python | 1 |
from .admin import *
from .user import *
__all__ = admin.__all__ + user.__all__
| Python | 1 |
}
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug)]
pub struct ProjectBill {
pub id: i32,
pub projectId: i32,
pub beginDate: String,
pub endDate: String,
pub amount: i64,
pub orderNo: String,
pub status: i16,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct BillUpd... | Rust | 0 |
, 19),
2022: (OCT, 9),
2023: (SEP, 28),
2024: (SEP, 15),
}
# https://web.archive.org/web/20241231191036/https://www.timeanddate.com/holidays/oman/isra-miraj
ISRA_AND_MIRAJ_DATES = {
2018: (APR, 13),
2019: (APR, 3),
2020: (MAR, 22),
2021: (MAR, 11),
... | Python | 1 |
});
}
}
rx
}
fn poll_telemetry(
&mut self,
poller: &mut SerialPoller,
rx: &Receiver<TelemetryChannelType>,
) -> bool {
let mut has_poll_events = false;
'poll_serial: loop {
match poller.poll(rx) {
... | Rust | 0 |
{
pub focus_change: wl_signal,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_seat_pointer_grab {
pub interface: *const wlr_pointer_grab_interface,
pub seat: *mut wlr_seat,
pub data: *mut libc::c_void,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_pointer_grab_interface {
pub enter: Option... | Rust | 0 |
each(|x| *x = self.payload_pattern.0);
let mut req = MutableEchoRequestPacket::new(&mut icmp_buf[..icmp_buf_size]).req()?;
req.set_icmp_type(IcmpTypes::EchoRequest);
req.set_icmp_code(echo_request::IcmpCodes::NoCode);
req.set_identifier(self.identifier.0);
req.set_payload(&payloa... | Rust | 0 |
1, // SBC A, (HL)
// TODO: Test
0x9f => sbc_a_r!(a), // SBC A, A
0xa0 => and_r!(b), 0xa1 => and_r!(c), 0xa2 => and_r!(d),
0xa3 => and_r!(e), 0xa4 => and_r!(h), 0xa5 => and_r!(l),
0xa6 => and_hl!(), 0xa7 => and_r!(a),
0xa8 => xor_r!(b), 0xa9 => xo... | Rust | 0 |
lista = [10, 5, "ciao", 210, "python", 15]
print(lista)
lista.append("ciccio")
print(lista)
lista.remove(10)
print(lista)
elemento = lista[0]
print(elemento)
sottolista = lista[2:4]
print(sottolista)
sottolista = lista[:4]
print(sottolista)
sottolista = lista[2:]
print(sottolista)
lista2 = lista + sottolista
pri... | Python | 1 |
# ship_types.py
SHIP_TYPES = {
0: "N/A",
1: "Reservert",
2: "Reservert",
3: "Reservert",
4: "Reservert",
5: "Reservert",
6: "Reservert",
7: "Reservert",
8: "Reservert",
9: "Reservert",
10: "Reservert",
11: "Reservert",
12: "Reservert",
13: "Reservert",
14: "Re... | Python | 1 |
let mut arr: [MaybeUninit<T::Item>;N] = MaybeUninit::uninit().assume_init();
for i in (0..N).rev() {
arr[i].write(window.pop().unwrap());
}
let arr: [T::Item;N] = (&arr as *const _ as *const [T::Item; N]).read();
... | Rust | 0 |
from app import app, db
from app.models import User
from werkzeug.security import generate_password_hash
# Crear una aplicación de contexto para ejecutar comandos directamente con Flask
with app.app_context():
# Revisar si el usuario admin ya existe
admin = User.query.filter_by(username='admin').first()
if... | Python | 1 |
import FWCore.ParameterSet.Config as cms
##____________________________________________________________________________||
caloMet = cms.EDProducer(
"CaloMETProducer",
src = cms.InputTag("towerMaker"),
alias = cms.string('caloMet'),
noHF = cms.bool(False),
globalThreshold = cms.double(0.3),
calc... | Python | 1 |
Found 4 generator definitions in the repository",
"severity": "info",
"timestamp": datetime(2025, 1, 18, 22, 12, 21, 259186, tzinfo=timezone.utc),
},
{
"message": "Processing generator update_upstream_interfaces_description (generators/upstream_int... | Python | 1 |
}
impl EditWeight for &str {
fn add_cost(&self) -> usize {
1
}
fn rm_cost(&self) -> usize {
1
}
fn sub_cost(&self, other: &Self) -> usize {
if self == other {
0
} else {
1
}
}
}
/// Compute the Levenshtein distance between two seq... | Rust | 0 |
// pub fn GetFontResourceInfoW();
// pub fn GetFontUnicodeRanges();
// pub fn GetGlyphIndicesA();
// pub fn GetGlyphIndicesW();
// pub fn GetGlyphOutline();
// pub fn GetGlyphOutlineA();
// pub fn GetGlyphOutlineW();
// pub fn GetGraphicsMode();
// pub fn GetICMProfileA();
// pub fn ... | Rust | 0 |
import theano, cPickle, h5py, lasagne, random, csv, gzip
import numpy as np
import theano.tensor as T
# convert csv into format readable by rmn code
def load_data(span_path, metadata_path):
x = csv.DictReader(gzip.open(span_path, 'rb'))
wmap, cmap, bm... | Python | 1 |
[], dtype=np.float64)
with pytest.raises(ValueError):
cy_hmm_mod.TransitionModel.make_dense(states, pointers, probabilities)
with pytest.raises(ValueError):
nb_hmm_mod.TransitionModel.make_dense(states, pointers, probabilities)
# ---------------------------------------------------------------... | Python | 1 |
ome(group_name)),
);
}
s.send(ChannelData {
server_items: grouped_items.into_iter().cloned().collect(),
group_start_indexes,
databases_for_websites,
websites_for_databases,
... | Rust | 0 |
one_mut::<&mut IntersectionQueue2>(&rhs_data.entity)
{
queue.intersecting_started.push(lhs);
}
} else {
if let Ok(queue) = cx
.world
.query_one_mut::<&mut IntersectionQueue2>(&lhs_data.entity)
... | Rust | 0 |
ind, loc))
}
}
impl Parsable for Binding {
fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<Binding>> where L: Iterator<Item=Result<Located<Token>>> {
use Token::*;
let mut loc = consume_token(lexer, Begin)?;
let id = Symbol::parse(lexer)?;
let term = Term::parse(lexer)?;
loc = loc.union(consume_toke... | Rust | 0 |
import os
import uuid
from flask import Blueprint, request, jsonify, current_app
from werkzeug.utils import secure_filename
from flask_jwt_extended import jwt_required
from config import Config
from utils.image_tools import delete_image_file
upload_bp = Blueprint('upload', __name__, url_prefix='/upload')
def allowed_... | Python | 1 |
from types import FunctionType
from Script.Core import cache_control, game_type, get_text, flow_handle, text_handle, constant, py_cmd
from Script.Design import handle_premise, attr_calculation, map_handle
from Script.UI.Moudle import draw, panel
from Script.Config import game_config, normal_config
import random
cache... | Python | 1 |
uct a value from given reflective value.
///
/// # Panics
///
/// If reflective value is of incompatible type.
fn from_value_box(value_box: ReflectValueBox) -> Result<Self, ReflectValueBox> {
Self::RuntimeType::from_value_box(value_box)
}
/// Write the value.
fn set_from_value_b... | Rust | 0 |
=> write_minify("ayu.css", static_files::themes::AYU)?,
_ => {
// Handle added third-party themes
let filename = format!("{}.{}", theme, extension);
write_crate(&filename, &|| Ok(try_err!(fs::read(&entry.path), &entry.path)))?;
}
};
... | Rust | 0 |
nome = input("Digite seu nome: ")
none = nome
print("\nOla! " ,nome, ", bom dia!!! ")
print("\n" ,nome, "Sua fatura com vencimento em 9 de janeiro no valor de R$ 350,00 esta fechada. ") | Python | 1 |
#!/usr/bin/env python3
def somar(m1, m2):
matriz_soma = []
# Supondo que as duas matrizes possuem o mesmo tamanho
quant_linhas = len(m1) # Conta quantas linhas existem
quant_colunas = len(m1[0]) # Conta quantos elementos têm em uma linha
for i in range(quant_linhas):
# Cria uma nova linha ... | Python | 1 |
_dist: (array![2.8000000000000003, 6.4, 0.19999999999999973], 6.4)
},
l1_2: Payload {
penalty: L1::new(2.),
value: 25.2,
prox: (0., 8.4, -45.2),
subdiff_dist: (array![1.6, 5.2, 1.4], 5.2)
},
l1_1: Payload {
penalty: L1::new(1.),
value: 12.6,
prox... | Rust | 0 |
from lumibot.brokers import Alpaca
from lumibot.credentials import ALPACA_TEST_CONFIG
from lumibot.strategies.strategy import Strategy
"""
Strategy Description
A simple paper trading strategy that demonstrates how to use the register_cron_callback
method to schedule a function to be executed at a specific time. This... | Python | 1 |
tokio::main]
async fn main() {
let falcon = FalconHandle::from_env().await.expect("Could not authenticate with CrowdStrike API");
let crowd_score_response = crowd_score(&falcon.cfg, None, None, None, None).await.expect("Could not fetch CrowdScore");
if !crowd_score_response.errors.is_empty() {
epr... | Rust | 0 |
window, TITLE, title_rect.center_x(), title_rect.center_y());
// Render next piece preview
draw_text_centered(
&window,
"Next",
preview_frame_rect.center_x(),
preview_frame_rect.top - 1,
);
draw_frame(&window, &preview_frame_rect);
... | Rust | 0 |
import json
# Basic HID key mapping for letters (a-z)
# HID usage IDs for letters: 'a' = 4, 'b' = 5, ..., 'z' = 29
hid_map = {chr(i + 97): i + 4 for i in range(26)}
# Correct mapping for numbers (USB HID):
# '1' -> 30, '2' -> 31, ..., '9' -> 38, '0' -> 39
digits_map = {str(i): 29 + i for i in range(1, 10)}
digits_map... | Python | 1 |
ProgressBarTotal, DownloadName)
return PayloadTotal, PayloadTotalLength, 0
def getPayloadByChunks(self, PayloadTotal, PayloadTotalLength, PayloadRecv, ConnectionId, TimeoutRecv, DownloadName, OutFile, ProgressBar, ProgressBarTotal):
PayloadChunkBuffer = PayloadRecv
ChunkPosition = 0
... | Python | 1 |
2+SK_2*Q2;
let (p_b, q_b) = bb;
let s = b_dbl_and_add(e, sk, q_b);
let s = add(e, p_b, s); // S:=PB+SK*QB;
iso_3_eb_basis(e, ab, s, eb)
}
/// Input: (Bobs) secret key sk, curve e, basis bb for the 3^EB torsion
/// Output: j-invariant of the image curve under 3^EB-isogeny (shared secret)
pub... | Rust | 0 |
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error> {
let Binders {
ref binders,
ref value,
} = *self;
write!(fmt, "for{:?} ", binders.debug())?;
Debug::fmt(value, fmt)
}
}
impl<I: Interner> Debug for ProgramClauseData<I> {
fn fmt(&self, fmt: &mu... | Rust | 0 |
os::{
raw::{c_char, c_int, c_long, c_ulong, c_ushort, c_void},
unix::io::{IntoRawFd, RawFd},
},
task::{Context, Poll},
};
use crate::Event;
// This input offset when subtracted, gives a platform-agnostic button ID.
// Since Stick only looks for gamepads and joysticks, button IDs below this
/... | Rust | 0 |
#!/usr/bin/env python3
"""
Test script for CQRS-compliant MCP Resources implementation.
This script tests the new Qdrant Resources that follow the CQRS pattern:
- Resources: Read-only operations (queries)
- Tools: Command operations (handled by existing MCP tools)
Usage:
python tests/integration/test_cqrs_resourc... | Python | 1 |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#任务队列GAE接口实现
#Author: cdhigh <https://github.com/cdhigh>
import os, json
from urllib.parse import urlencode, urlparse
appId = os.getenv('APP_ID', '') #google cloud库会patchos.environ,需要先获取环境变量
serverLoc = os.getenv('SERVER_LOCATION', '')
from google.cloud import tasks_v2
DEF... | Python | 1 |
/// - If the first 16 bytes of `c` a not zero.
/// - XXX: size of `c` vs `m`?
#[allow(clippy::result_unit_err)]
pub fn box_open(
m: &mut [u8],
c: &[u8],
n: &BoxNonce,
pk: &BoxPublicKey,
sk: &BoxSecretKey,
) -> Result<(), ()> {
assert_eq!(&c[..16], &[0u8; 16]);
/* FIXME: uninit in tweet-na... | Rust | 0 |
minal size needs to be at least 80x24!")
}
let mut screen = target.lock().unwrap();
screen.size_x = x;
screen.size_y = y - 1;
screen.unit_x = 1.0 / screen.size_x as f64;
screen.unit_y = 1.0 / screen.size_y as f64;
}
}
impl RenderEngine for Crossterm {
fn init(self: &Self) -> Result<(), Stri... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright 2016 Timothy Dozat
#
# 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 req... | Python | 1 |
as usize.
/// Uses the newtype index pattern.
/// <https://matklad.github.io/2018/06/04/newtype-index-pattern.html>
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct VertexIndex(pub usize);
impl Display for VertexIndex {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
write!(... | Rust | 0 |
Required features: 'Win32_Networking_WinInet'*"]
pub const INTERNET_CACHE_FLAG_ADD_FILENAME_ONLY: u32 = 2048u32;
#[doc = "*Required features: 'Win32_Networking_WinInet'*"]
pub const INTERNET_CACHE_FLAG_ALLOW_COLLISIONS: u32 = 256u32;
#[doc = "*Required features: 'Win32_Networking_WinInet'*"]
pub const INTERNET_CACHE_FL... | Rust | 0 |
"purchased")
assert list(lbl_feat_dict.keys()) == ["label", "features"]
assert_array_equal(
lbl_feat_dict["label"],
jxn.array([[False], [True], [True], [False], [True]], dtype=jxn.bool),
)
assert_array_equal(
lbl_feat_dict["features"],
jxn.array(
[
... | Python | 1 |
ructure(
_get_atomic_numbers(pymatgen_structure),
_get_lattice(pymatgen_structure),
get_positions(pymatgen_structure),
)
def construct_trajectory(
pymatgen_trajectory: pymatgen.core.trajectory.Trajectory,
timestep: float,
) -> Trajectory:
"""Create a Trajectory from a pymatgen ... | Python | 1 |
< idx_end <= 15 * 60 * fs:
pp_label.append(1)
else:
pp_label.append(2)
idx_start += stride
train_data["VF_"+record_name] = {"X": pp_data, "Y": pp_label}
path = '/home/lzy/workspace/codeFile/VFearlywarning/mit-b... | Python | 1 |
def update(self):
# Note, update should only start fetching,
# followed by asynchronous updates through notifications.
with self._dev:
self._dev.state()
def turn_on(self, **kwargs):
"""Turn the light on."""
self._state = True
with self._dev:
... | Python | 1 |
import tkinter as tk
import threading
import time
import win32api
import win32con
import win32gui
# 默认设置
FOCUS_INTERVAL = 1 # 单位:秒
POPUP_DURATION = 2 # 弹窗持续
MESSAGE = "Freeing up the time you waste on the computer"
# 活动检测
last_input_time = time.time()
lock = threading.Lock()
def get_last_input_time():
# ... | Python | 1 |
elf.filtered_games, "all")
self.populate_favorites_list()
self.populate_deleted_list()
# Update stats
total_games = len(self.games)
favorites_count = len(self.favorites)
deleted_count = len(self.deleted_games)
stats_text = f"📊 {total_games} Game... | Python | 1 |
::SYSCFG => unsafe {
RCC.enable_syscfg_clock();
},
PCLK2::USART1 => unsafe {
RCC.enable_usart1_clock();
},
PCLK2::SPI1 => unsafe {
RCC.enable_spi1_clock();
},
},
... | Rust | 0 |
otobuf::Clear for ActionMultiPanel {
fn clear(&mut self) {
self.clear_field_type();
self.clear_unit_index();
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for ActionMultiPanel {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_f... | Rust | 0 |
or truncated
obs_key = new_obs_key
ep_cum_rewards.append(cumulated_reward)
avg_cumulated_reward = np.mean(ep_cum_rewards)
print(f"Evaluation finished with avg. cum. reward: {avg_cumulated_reward}")
return avg_cumulated_reward, ep_cum_rewards
if __name__... | Python | 1 |
g from file we want ne not to have transformations.
# Both ne and the boundary condition are given in absolute values (not fGW).
# Additionally we want to avoid normalizing to nbar.
runtime_params.profile_conditions.n_e_right_bc_is_fGW = False
runtime_params.profile_conditions.n_e_nbar_is_fGW = False
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.