text string | label_name string | labels int64 |
|---|---|---|
from pydantic import BaseModel, Field, field_validator, SerializeAsAny
from oshconnect.csapi4py.constants import ObservationFormat
from oshconnect.datamodels.encoding import Encoding
from oshconnect.datamodels.swe_components import AnyComponentSchema
class DatastreamSchema(BaseModel):
"""
A class to represen... | Python | 1 |
ive {
match self.owner {
Owner::Player => self.y -= 1,
Owner::Aliens => self.y += 1,
}
self.timer.reset();
}
}
pub fn explode(&mut self) {
self.alive = false;
self.timer = Timer::from_millis(200);
}
pub fn ready_to_clear(&self) -> bool {
match self.owner {
... | Rust | 0 |
vent_data),
"::",
stringify!(error)
)
);
}
pub type vea_event_data_t = vea_event_data;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct vea_event {
pub event_type: vea_event_type_t,
pub event_data: vea_event_data_t,
}
#[test]
fn bindgen_test_layout_vea_event() {
assert_eq!(
... | Rust | 0 |
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2
"#;
let input = parse_input(input);
let expected = 12;
let actual = part1(&input, 10, true);
assert_eq!(expected, actual);
}
}
<gh_stars>0
//! [![github]](https://github.com/mathiversen/d4t4)
//!... | Rust | 0 |
-1);
}
}
use cranelift_codegen::cursor::FuncCursor;
use cranelift_codegen::ir;
use cranelift_codegen::ir::immediates::{Imm64, Offset32};
use cranelift_codegen::ir::types::*;
use cranelift_codegen::ir::{
AbiParam, ArgumentPurpose, ExtFuncData, ExternalName, FuncRef, Function, InstBuilder, Signature,
};
use cran... | Rust | 0 |
import numpy as np
def inspect_npz_file(file_path):
"""
Affiche les tableaux contenus dans un fichier .npz et leurs shapes.
Args:
file_path (str): Chemin vers le fichier .npz.
"""
try:
# Charger le fichier .npz
data = np.load(file_path)
# Afficher les n... | Python | 1 |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------
# aihub.cloud.google.com Assignment
# ----------------------------------------------------------------
import pandas as pd
# ------------------- STEP 1: 按照要求计算下方题目结果 -------------------
# Q1: 机器翻译是将一个语言序列转换为另一个语言序列的典型任务。
# 在Hu... | Python | 1 |
import sys
sys.path.append('..')
import os
import requests
import torch
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import glob
import models_mae
from torchvision import transforms
def show_image(image, title=''):
# image is [H, W, 3]
# assert image.shape[2] == 3
plt.imshow(ima... | Python | 1 |
"""
Write a function to find the median length of a trapezium.
assert median_trapezium(15,25,35)==20
"""
def median_trapezium(a, b, c):
# Calculate the area of the trapezium using the formula: area = (a + b) * h / 2
h = (2 * area(a, b, c)) / (a + b)
# The median is the height, so just return it
return h... | Python | 1 |
XLAN_UDP_ZERO_CSUM6_RX: u16 = 20;
const IFLA_VXLAN_REMCSUM_TX: u16 = 21;
const IFLA_VXLAN_REMCSUM_RX: u16 = 22;
const IFLA_VXLAN_GBP: u16 = 23;
const IFLA_VXLAN_REMCSUM_NOPARTIAL: u16 = 24;
const IFLA_VXLAN_COLLECT_METADATA: u16 = 25;
const IFLA_VXLAN_LABEL: u16 = 26;
const IFLA_VXLAN_GPE: u16 = 27;
const IFLA_VXLAN_TT... | Rust | 0 |
import pygame, sys
pygame.init()
WINDOW_WIDTH, WINDOW_HEIGHT = 1280,720
display_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('Meteor shooter')
clock = pygame.time.Clock()
# importing images
ship_surf = pygame.image.load('../graphics/ship.png').convert_alpha()
ship_y_pos... | Python | 1 |
_result);
}
};
}
/// Implement a test which performs a filter over a `ParallelIterator` and over its correspondant `Iterator`,
/// and compares that the result of both iterators is the same. It performs over iterators which return
/// &str.
///
/// # Input
///
/// te... | Rust | 0 |
------------------------------------------------------
fn fps(&self) -> u32 {
self.frame_rate
}
fn set_fps(&mut self, frame_rate: u32) {
self.frame_rate = frame_rate;
// TODO set timer / frame rate?
//self.timer.set_speed(1.0 / frame_rate as f64);
}
fn tick_rate(&s... | Rust | 0 |
or acc in f:
print(f'{lg}[{i}] {acc[3]} {acc[4]} {n}')
i += 1
index = int(input(f'\n{lg}[+] Введите выбор: {n}'))
acc_to_change = int(accs[index][0])
phone = accs[index][3]
update_tgaccounts(accs[index][0], pole='banned')
f = get_all_tgaccounts()
f... | Python | 1 |
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | Python | 1 |
from typing import NamedTuple
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from ..utils import CI_MatrixSolution, QISKIT_STATE
from ..utils import PaddingType
from .. import pulses
def CA_region(center: float) -> tuple[float, float]:
CA = 0.0016
return center - CA, center + ... | Python | 1 |
fn connector(&self) -> Box<dyn Connector>;
fn allowed_referential_integrity_settings(&self) -> BitFlags<ReferentialIntegrity> {
use ReferentialIntegrity::*;
ForeignKeys | Prisma
}
fn default_referential_integrity(&self) -> ReferentialIntegrity {
ReferentialIntegrity::ForeignKeys
... | Rust | 0 |
latest ticker indicators from all active Luno exchanges.
pub async fn list_tickers(&self) -> Result<Vec<Ticker>, LunoError> {
let url = self.url_maker.tickers();
Ok(self.get::<ListTickersResponse>(url).await?.tickers)
}
/// Returns a list of the top 100 bids and asks in the order book.
/// Ask orders are sort... | Rust | 0 |
font.to_string());
println!();
println!("```text");
for x in &font.byte_array() {
for bit in 0..8 {
match *x & 1 << bit {
0 => print!("░"),
_ => print!("█"),
}
... | Rust | 0 |
import datetime
from os import environ
#Dont Remove My Credit @Silicon_Bot_Update
#This Repo Is By @Silicon_Official
# For Any Kind Of Error Ask Us In Support Group @Silicon_Botz
class Config:
API_ID = environ.get("API_ID", "26741021")
API_HASH = environ.get("API_HASH", "7c5af0b88c33d2f5cce8df5d82eb2a94")... | Python | 1 |
import os
import argparse
import numpy as np
from collections import defaultdict
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
parser = argparse.ArgumentParser('Deformable DETR Detector', add_help=False)
parser.add_argument('--det_root', default='tracker', type=str)
args = parser.parse_a... | Python | 1 |
DESCRIPTOR = _NODE,
__module__ = 'tensorflow.core.profiler.op_profile_pb2'
# @@protoc_insertion_point(class_scope:tensorflow.profiler.op_profile.Node)
))
_sym_db.RegisterMessage(Node)
_sym_db.RegisterMessage(Node.InstructionCategory)
_sym_db.RegisterMessage(Node.XLAInstruction)
_sym_db.RegisterMessage(Node.XLAIn... | Python | 1 |
cimal_division_in_256, decimal_multiplication_in_256, decimal_summation_in_256,
uint128_to_decimal,
};
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{
to_binary, Addr, Binary, Coin, Deps, DepsMut, Env, MessageInfo, Order, Response, StakingMsg,
StdError, StdResult, Storage... | Rust | 0 |
"""
Representation for a resolved Context.
.. module:: resolved_context
:synopsis: Creates a ContextResolver
.. moduleauthor:: Dave Longley
.. moduleauthor:: Gregg Kellogg <gregg@greggkellogg.net>
"""
from cachetools import LRUCache
MAX_ACTIVE_CONTEXTS = 10
class ResolvedContext:
"""
A cached contex docu... | Python | 1 |
_are_ignored() -> Result<(), ScannerError> {
assert_eq!(scan(" \t\n+")?, vec![Token::Plus]);
Ok(())
}
#[test]
fn single_digit_number() -> Result<(), ScannerError> {
assert_eq!(scan("1")?, vec![Token::Number(1.0)]);
Ok(())
}
#[test]
fn multi_digit_integer() -> Re... | Rust | 0 |
})
.unwrap();
{
let mut guard = obj_ref.lock().unwrap();
*guard = env.new_global_ref(bi_function).unwrap();
}
let actual_ret = env
.call_method(
bi_function,
"apply",
... | Rust | 0 |
import asyncio
from collections.abc import Callable
from dataclasses import dataclass
from src.chat.message_receive.message import MessageRecvS4U
from src.common.logger import get_logger
logger = get_logger("gift_manager")
@dataclass
class PendingGift:
"""等待中的礼物消息"""
message: MessageRecvS4U
total_count... | Python | 1 |
ST_CITIES,
},
"Bushehr" => Province{
prefix_phone : "077",
farsi_name : "",
latin_name : "",
cities : &BUSHEHR_CITIES,
},
"ChaharMahaalAndBakhtiari" => Province{
prefix_phone : "038",
farsi_name : "",
latin_name : "",
cities : &CHAHARMAHAAL... | Rust | 0 |
files"))
except: pass
rx_binding = re.compile(r'(?P<module>[A-Za-z0-9_\.-]+)(:(?P<profile>[A-Za-z0-9_-]+))?$')
bindings_dir = os.path.join(self.env.SEISCOMP_ROOT, "etc", "key")
key_dir = os.path.join(bindings_dir, self.name)
config_file = os.path.join(self.config_dir, "slarchive.streams")
#... | Python | 1 |
t(",").collect::<Vec<&str>>();
println!("{:?}", routes);
let mut earliestRoute = std::i64::MAX;
let mut earliestRouteIdx = -1;
let mut accum = 0;
let mut inc = 1;
for (i, route) in routes.iter().enumerate() {
match route {
&"x" => {},
_ => {
le... | Rust | 0 |
"""Set commands utils"""
import asyncio
from app.utils.config import Settings
from app.database.models import User
from app.templates.keyboards import ADMIN_COMMANDS, USER_COMMANDS
from typing import Optional
from contextlib import suppress
from aiogram import Bot, exceptions
from aiogram.types import BotCommandScop... | Python | 1 |
2BIT_CARGO_TARGET}')
env = os.environ.copy()
if INSTRUMENT_FUZZING:
if ORIG_CC is not None:
env['CC'] = ORIG_CC
else:
del env['CC']
if ORIG_CXX is not None:
env['CXX'] = ORIG_CXX
else:
del env['CXX']
subprocess.check_call(
... | Python | 1 |
# **************************************************************************** #
# #
# ::: :::::::: #
# 12_reg.py :+: :+: :+: ... | Python | 1 |
class Solution:
def solveNQueens(self, n: int) -> list[list[str]]:
diag_pos_set = set()
diag_neg_set = set()
cols_set = set()
board = [[False] * n for _ in range(n)]
result = []
def place_queen(row: int) -> None:
if row == n:
result.appen... | Python | 1 |
t::<ArrayVec<[u8; MAX_HASH_SIZE]>>();
H::default()
.chain(&key)
.chain(&IPAD_ARRAY[H::OUTPUT_SIZE.into()..H::BLOCK_SIZE.into()])
}
fn compute_hmac_opad<H: HashChain>(hasher: &mut H, key: &[u8]) -> ArrayVec<[u8; MAX_HASH_SIZE]> {
const OPAD_ARRAY: [u8; MAX_HASH_BLOCK_SIZE] = [OPAD; MAX_HASH_BLO... | Rust | 0 |
s=EPSG:99999&format=image%2Fjpeg&styles=&width=512&height=512&bbox=-180,-198,108,90&time={}'.format(
base_url, self.endpoint_prefix_twms,
self.endpoint_prefix_twms + '_date', date)
check_result = check_tile_request(req_url, ref_hash)
self.assertTrue(
check_result,
... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
import qiskit
from qiskit.circuit import Parameter
import qiskit_aer
# Create a parameterized quantum circuit
theta = Parameter('θ')
qc = qiskit.QuantumCircuit(2)
qc.h(0)
qc.cry(theta, 0, 1)
qc.measure_all()
# Activate the GPU capability
backend = qiskit_aer.AerSimu... | Python | 1 |
ric="manhattan")
clf.fit(X, y)
dense_centroid = clf.centroids_
clf.fit(X_csr, y)
assert_array_equal(clf.centroids_, dense_centroid)
assert_array_equal(dense_centroid, [[-1, -1], [1, 1]])
# TODO(1.5): remove this test
@pytest.mark.parametrize(
"metric", sorted(list(NearestCentroid._valid_metric... | Python | 1 |
ofile_Base: eAVEncH264VProfile = 66i32;
#[doc = "*Required features: 'Win32_Media_MediaFoundation'*"]
pub const eAVEncH264VProfile_Main: eAVEncH264VProfile = 77i32;
#[doc = "*Required features: 'Win32_Media_MediaFoundation'*"]
pub const eAVEncH264VProfile_High: eAVEncH264VProfile = 100i32;
#[doc = "*Required features: ... | Rust | 0 |
{
CHANNEL5_W { w: self }
}
#[doc = "Bit 6 - Select secure attribute."]
#[inline(always)]
pub fn channel6(&mut self) -> CHANNEL6_W {
CHANNEL6_W { w: self }
}
#[doc = "Bit 7 - Select secure attribute."]
#[inline(always)]
pub fn channel7(&mut self) -> CHANNEL7_W {
C... | Rust | 0 |
int) & 0x1fff as c_int;
if id13field_1 != 0 {
mm.b_flags |= (1 as c_int) << 5 as c_int;
mm.mode_a = decode_id13_field(id13field_1)
}
}
} else if !(metype == 29 as c_int) {
if !(metype == 3... | Rust | 0 |
def __getattr__(self, item):
if hasattr(self.scheduler, item):
return getattr(self.scheduler, item)
else:
return getattr(self, item)
| Python | 1 |
Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, 'parlai', 'ParlAI Documentation', [author], 1)]
# -- Options for Texinfo output -----------------------------... | Python | 1 |
(end, 0);
// 1 extra to leave room for written_extra
self.written
.resize(end / 8 + (end % 8 != 0) as usize + 1, !0);
}
for (i, b) in data.iter().enumerate() {
let position = start + i;
self.data[position] = *b;
let bit = self.w... | Rust | 0 |
song_name
})
await msg.ctx.channel.send("已添加")
except:
pass
@bot.command(name="RELOAD")
async def reload(msg: Message):
global config
global firstlogin
global netease_phone
global netease_pa... | Python | 1 |
(format!("No active transaction")))?;
tx.input.send(TransactionRequest::Commit).await?;
tx.handle.await?
}
}
extern crate engine_display;
extern crate rand;
use std::thread;
use std::time::Duration;
use rand::Rng;
use engine_display::EngineDisplay;
// N.B. This is purely a demo/testing bin targ... | Rust | 0 |
CHANNEL_PROPERTY_ID = 4i32;
#[doc = "*Required features: `\"Win32_Networking_WindowsWebServices\"`*"]
pub const WS_CHANNEL_PROPERTY_ENVELOPE_VERSION: WS_CHANNEL_PROPERTY_ID = 5i32;
#[doc = "*Required features: `\"Win32_Networking_WindowsWebServices\"`*"]
pub const WS_CHANNEL_PROPERTY_ADDRESSING_VERSION: WS_CHANNEL_PROP... | Rust | 0 |
momentum = total_batch.clamp(max=1) * self.momentum # no update if total_batch is 0
total_batch = torch.max(total_batch, torch.ones_like(total_batch)) # avoid div-by-zero
mean, meansqr, _ = torch.split(vec / total_batch, C)
var = meansqr - mean * mean
invstd = tor... | Python | 1 |
"""
Dynamically imports all Python modules in this directory (excluding __init__.py).
Triggers decorator-based registration (e.g., for tools or prompt modifiers).
"""
import importlib
import pathlib
current_dir = pathlib.Path(__file__).parent
for path in current_dir.glob("*.py"):
if path.name == "__init__.py":
... | Python | 1 |
from scipy import stats
>>> from statsmodels.distributions.discrete import (
DiscretizedCount, DiscretizedModel)
>>> dd = DiscretizedCount(stats.gamma)
>>> mod = DiscretizedModel(y, distr=dd)
>>> res = mod.fit()
>>> probs = res.predict(which="probs", k_max=5)
"""
def __init__(s... | Python | 1 |
ensorflow",
reason="Need sparse tensor support.",
)
def test_sparse_input_fails(self):
with self.assertRaisesRegex(
ValueError, "inputs should be dense tensors"
):
sparse_in = tf.sparse.from_dense(np.array([1]))
layers.HashedCrossing(num_bins=10)((spar... | Python | 1 |
from django import forms
from .models import Rooms, User
from django.contrib.auth.forms import UserCreationForm
class MyUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ['name', 'username', 'email', 'password1', 'password2']
widgets = {
'name': forms.TextIn... | Python | 1 |
.signer_account_pk = public_key(2).into();
testing_env!(context.clone());
// Selecting staking pool
let staking_pool = "staking_pool".to_string();
testing_env!(context.clone());
contract.select_staking_pool(staking_pool.clone());
context.predecessor_account_id = lockup_... | Rust | 0 |
()
}
pub fn iter_depth_pix(self) -> DepthPixIter<T> {
DepthPixIter::<T>::new(self.ranges)
}
pub fn union(&self, other: &Self) -> Self {
let ranges = self.ranges.union(&other.ranges);
NestedRanges { ranges }
}
pub fn intersection(&self, other: &Self) -> Self {
l... | Rust | 0 |
ttings in the engine match the
// compilation settings of the module that's being loaded.
self.check_triple(engine)?;
self.check_shared_flags(engine)?;
self.check_isa_flags(engine)?;
self.check_tunables(&engine.config().tunables)?;
self.check_features(&engine.config().fe... | Rust | 0 |
# first party
from delphi.epidata.common.integration_test_base_class import DelphiTestBase
class SignalDashboardTest(DelphiTestBase):
"""Basic integration tests for signal_dashboard_coverage and signal_dashboard_status endpints."""
def setUp(self) -> None:
"""Perform per-test setup."""
self.... | Python | 1 |
qWindowOpen");
self.InterruptGuest();
//self.vcpu.set_kvm_request_interrupt_window(0);
}
VcpuExit::Intr => {
//self.vcpu.set_kvm_request_interrupt_window(1);
SHARE_SPACE.MaskTlbShootdown(self.id as _);
... | Rust | 0 |
ez::graphics::Image,
) -> ggez::GameResult<ggez::graphics::Mesh> {
use ggez::graphics::Mesh;
match self.indices.as_ref() {
Some(indices) => Mesh::from_raw(ctx, &self.vertices, indices, Some(texture)),
None => Err(ggez::GameError::CustomError(
"Unindexed meshes... | Rust | 0 |
.0001,
}
args.lr = lrs[args.dataset.lower()] / (4 * len(args.gpu_ids)) * args.batch_size
if args.checkname is None:
args.checkname = 'RFNet'
print(args)
torch.manual_seed(args.seed)
trainer = Trainer(args)
print('Starting Epoch:', trainer.args.start_epoch)
print('Total ... | Python | 1 |
88\x09\x91:\
\xe8\xd8U\x1c\x8f\x01\x90\xbe\x13b?\xc1\xb1\xeaK\x9c\
\xc4 &\xbf\xa9\xd7V[\xe6z\xee\x19\x09\x1dC\xff\
]\xe3\x8f>\x5c\x96\x84E\xbd\x87e\xf43\x03)\xcf\
\xbf\x867u\x0e\xbf\x15mk\xbf\x8b\x9f\xf94\xd7\x89\
D\xe2\xb1\x80\xcd\x04w\x98\xa1\x8f\x97\xcd\xae\xaa\xad\x81\
\xd0Y\xce\x09\x8e\x10<\x01\xc4u\x87\xe7\xf5\xf... | Python | 1 |
: u8 = 0;
// Late Resources
static EXTCOMIN: display::Extcomin;
static DISPLAY: display::Display;
static BLE: ble::Ble;
},
tasks: {
TIM7: {
path: tick,
resources: [TOGGLE, EXTCOMIN, DISPLAY],
},
SYS_TICK: {
path: sys_... | Rust | 0 |
: HashMap::default(),
order: &sset.order,
nameset: names,
gnames: NameReader::new(names),
local_vars: HashMap::default(),
local_floats: HashMap::default(),
local_dv: Vec::new(),
local_essen: Vec::new(),
frames_out: Vec::new(),
};
for sref in seg {... | Rust | 0 |
let coord1_without = Coord::new(-1.1, -0.1, -0.1);
let coord2_without = Coord::new(1.1, 1.1, 1.1);
let coords_without = vec![coord1_without, coord2_without];
let coords = coords_within
.iter()
.chain(coords_without.iter())
.cloned()
.colle... | Rust | 0 |
downsample = None
if stride != 1 or self.in_channel != channel * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.in_channel, channel * block.expansion, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(channel * block.expansion))
layer... | Python | 1 |
if resource_reference.is::<HtmlElement>() {
let html_element: &HtmlElement = resource_reference.downcast_ref().unwrap();
let node: &'static Node =
unsafe { mem::transmute::<&Node, &'static Node>(html_element.as_ref()) };
Ok(node)
} else if resource_reference.is::<HtmlTableEleme... | Rust | 0 |
nreachable code
}
fn main() {
let v: Void = unsafe {
std::mem::transmute::<(), Void>(())
};
f(v); //~ inside call to `f`
}
<filename>shared/rust/src/domain/jig/module/body.rs
use super::ModuleKind;
use crate::{
domain::{audio::AudioId, image::ImageId},
media::MediaLibrary,
};
use serde::{de... | Rust | 0 |
#User function Template for python3
class Solution:
def kthElement(self, k, A, B):
if len(A) > len(B) :
A , B = B , A
left = k
n1 , n2 = len(A) , len(B)
l = max(0 , k - n2)
r = min(n1 , k)
while l <= r :
mid1 = (... | Python | 1 |
[test]
fn should_return_object_already_existing_error_in_case_of_422_status_code() {
// Arrange
let director_server = MockServer::start();
let server_response = "{\"error\": \"Trying to recreate icinga_host (\"some host\")\"}";
Mock::new()
.expect_method(POST)
.expect_path("/host")
... | Rust | 0 |
th_rule_pipeline() {
// Load SUDT contract
let mut sudt_contract = gen_sudt_contract(None, None);
// Create SUDT Cell Output
let sudt_cell = generate_simple_udt_cell(&sudt_contract);
// Mock Transaction with a single output
let transaction = generate_mock_tx(vec![sudt_cell], vec![2000_u128.to_le... | Rust | 0 |
# ATIVIDADE 6
#|O cardápio da Lanchonete Bom Apetite é o seguinte:
""" Código do Lanche Especificação Preço
Unitário(R$)
100 Cachorro quente 2,50
101 Bauru simples 2,00
102 ... | Python | 1 |
ESYS_TR,
inData: *const TPM2B_SENSITIVE_DATA,
) -> TSS2_RC;
}
extern "C" {
pub fn Esys_StirRandom_Finish(esysContext: *mut ESYS_CONTEXT) -> TSS2_RC;
}
extern "C" {
pub fn Esys_HMAC_Start(
esysContext: *mut ESYS_CONTEXT,
handle: ESYS_TR,
shandle1: ESYS_TR,
shandle2: E... | Rust | 0 |
import pytest
import numpy as np
import sympy as sp
from shenfun import FunctionSpace, TensorProductSpace, TrialFunction, div, grad, \
curl, comm, VectorSpace, Function, inner, \
BlockMatrix, TestFunction as _TestFunction
def get_function_space(space='cylinder'):
if space == 'cylinder':
r, theta, z... | Python | 1 |
_key();
assert_eq!(*expected_public_key, public_key);
}
fn test_to_address<N: BitcoinNetwork>(
expected_address: &BitcoinAddress<N>,
expected_format: &BitcoinFormat,
private_key: &BitcoinPrivateKey<N>,
) {
let address = private_key.to_address(expected_format).unwrap(... | Rust | 0 |
"""Serachers unit tests
"""
import pytest
import pandas as pd
@pytest.mark.parametrize(
"raw_html, clean_text",
[
("<div><a>Any text</a></div>", "Any text"),
("<div><div><p>Any text</a></div>", "Any text"),
("Any text</a></div>", "Any text"),
("Any text", "Any text"),
... | Python | 1 |
type LPWSADATA = *mut WSADATA;
#[link(name = "ws2_32")]
extern "system" {
fn WSAStartup(wVersionRequested: libc::WORD,
lpWSAData: LPWSADATA) -> libc::c_int;
}
unsafe {
use std::unstable::mutex::{Once, ONCE_INIT};
static mut INIT: Once = ONCE_INIT;
... | Rust | 0 |
placing one category with another
Category::update_crate(&app.diesel_database.get().unwrap(), &krate, &["category-2"]).unwrap();
assert_eq!(cnt!(&mut req, "cat1"), 0);
assert_eq!(cnt!(&mut req, "category-2"), 1);
// Removing one category
Category::update_crate(&app.diesel_database.get().unwrap(), &... | Rust | 0 |
_e y )N r PC:\Users\CA9\Desktop\service app project\backend\customapp\customapp\__init__.py<module>r s r | Python | 1 |
import os
import streamlit as st
st.set_page_config(page_title="Personal Library Manager", page_icon="📚")
st.markdown("""
<style>
.main-container {
max-width: 80%;
margin: auto;
transition: max-width 0.1s ease-in-out;
}
.sidebar-hidden .main-container {
max-width: 100%;
... | Python | 1 |
f32, PdfSpace> {
let Point { x, y } = self;
euclid::Vector2D::new(x, y)
}
}
#[cfg(feature = "euclid")]
impl From<euclid::Vector2D<f32, PdfSpace>> for Point {
fn from(from: euclid::Vector2D<f32, PdfSpace>) -> Self {
let euclid::Vector2D { x, y, .. } = from;
Point { x, y }
}
... | Rust | 0 |
,
r,
bias,
sl,
initial_h,
linear_before_reset,
})
.boxed()
}
}
impl GruProblem {
fn i(&self) -> usize {
self.x.shape()[2]
}
fn b(&self) -> usize {
self.x.shape()[1]
}
fn lower... | Rust | 0 |
="plasma",
vmin=f.min(),
vmax=f.max(),
)
else:
plt.contourf(
x[..., 0],
x[..., 1],
f,
levels=levels,
cmap="plasma",
vmin=f.min(),
vmax=f.max(),
... | Python | 1 |
: &'a [u8], _ctx: ()) -> result::Result<(Self, usize), Self::Error> {
let o = 0;
let offset = &mut 0;
let mut result = 0;
let mut shift = 0;
let size = 64;
let mut byte: u8;
loop {
byte = src.gread(offset)?;
if shift == 63 && byte != 0x00 ... | Rust | 0 |
}
}
#[derive(Debug, Deserialize)]
struct ResponseBody {
values: Vec<Bson>,
}
<gh_stars>1-10
//! Tests of [`rustls::KeyLogFile`] that require us to set environment variables.
//!
//! vvvv
//! Every test you add to this file MUST execute through `serialized()`.
//! ... | Rust | 0 |
#[error("Invalid deny option for proposal")]
InvalidDenyOptionForProposal,
/// Option equal to deny option
#[error("Option equal to deny option")]
OptionEqualToDenyOption,
/// Invalid delegation state for updates
#[error("Invalid delegation state for updates")]
InvalidDelegationStateForUpd... | Rust | 0 |
nd',expandExpression=1,expandDescription=1)
if triggers:
if args.extended:
# print ids and descriptions
for trigger in triggers:
print(format(trigger["triggerid"])+":"+format(trigger["value"])+":"+format(trigger["status"])+":"+format(trigger["state"])+":"+format(trigger["priority"])+":"+format(... | Python | 1 |
xPlt]
yPlt = xPlt @ theta
model, = ax[1].plot(restore(xPlt[:, 1], mean, std).T, yPlt, color='green')
res = ax[1].scatter([1], [1], color='green')
modelArmijo, = ax[1].plot(restore(xPlt[:, 1], mean, std).T, yPlt, color='blue')
resArmijo = ax[1].scatter([1], [1], color='blue')
ax[0].legend(['fixed... | Python | 1 |
veProperties, BaseFractionalDerivative
class MockDerivative(BaseFractionalDerivative):
def compute(self, function, x, **kwargs):
return np.zeros_like(x)
def compute_numerical(self, function, x, **kwargs):
return np.zeros_like(x)
#... | Python | 1 |
, _model: &mut Model, _update: Update) {}
fn view(_app: &App, _model: &Model, frame: &Frame) {
frame.clear(SKYBLUE);
}
fn window_event(_app: &App, _model: &mut Model, event: WindowEvent) {
match event {
KeyPressed(_key) => {}
KeyReleased(_key) => {}
MouseMoved(_pos) => {}
Mouse... | Rust | 0 |
bwd_kernel_traits<96, 64, 128, 8, 2, 4, 4, true, false, cutlass::half_t, Flash_kernel"""
flash_attn_dtype = re.compile(r"cutlass::([a-zA-Z0-9_]+)")
fwd_pattern = re.compile("flash_fwd[a-zA-Z0-9_]+kernel")
bwd_pattern = re.compile("flash_bwd[a-zA-Z0-9_]+kernel")
bwd_commands = [
["nm", flash_attn... | Python | 1 |
perator == "<":
try:
return True if float(input) < float(value) else False
except Exception as e:
return True if input < value else False
elif operator == "≥":
try:
return True if float(input) >= float(value) else False
... | Python | 1 |
,
break_expired_at,
}
}
pub fn get_values(&'a self) -> (u16, &'a str, DateTime<Utc>, DateTime<Utc>, DateTime<Utc>) {
(
self.id,
self.description.as_str(),
self.created_at,
self.work_expired_at,
self.break_expired_at,
... | Rust | 0 |
d_instances)
def _remove_obico_instances(
self,
instance_list: List[MoonrakerObico],
) -> None:
if not instance_list:
Logger.print_info("No Obico instances found. Skipped ...")
return
for instance in instance_list:
Logger.print_status(
... | Python | 1 |
#encoding=utf-8
'''
此脚本用于合并batchnorm层,减少内存和计算时间.
训练完毕之后进行inference的时候可将全部的Conv-BN-Scale合并成一个Conv;
训练时可将被freeze的层合并,如果conv没被freeze,则仅合并BN-Scale
a tool to merge 'Conv-BN-Scale' into a single 'Conv' layer.
https://github.com/sanghoon/pva-faster-rcnn/blob/master/tools/gen_merged_model.py
也可参考这里的:https://github.com/NHZlX/Me... | Python | 1 |
import re
import os
import json
from pathlib import Path
import argparse
import logging
# from github import Github
def create_mapping(output_dir: Path, doc_dir_name: str):
mapping = {}
output_dir = output_dir.resolve()
script_dir = os.path.dirname(os.path.realpath(__file__))
directory = os.path.abspat... | Python | 1 |
&self.list_by {
query.push_kv("listBy", &smithy_http::query::fmt_string(&inner_15));
}
if self.max_results != 0 {
query.push_kv(
"maxResults",
&smithy_types::primitive::Encoder::from(self.max_results).encode(),
);
}
if ... | Rust | 0 |
"mqtt_qos invalid, must be between 0 and 2, but {} is configured",
conf.mqtt.qos
);
panic!();
}
}
}
<gh_stars>10-100
extern crate signal;
extern crate nix;
use std::time::{Instant, Duration};
use std::thread::sleep;
use nix::sys::signal::{SIGINT};
... | Rust | 0 |
Test18EE.crt";
// pkits_data_map
// .entry("4.14")
// .or_insert_with(Vec::new)
// .push(PkitsTestCase {
// target_file_name,
// intermediate_ca_file_names,
// settings: &G_DEFAULT_SETTINGS,
// ta5914_filename: &... | Rust | 0 |
#!/usr/bin/env python3
"""
🏛️ Authenticated Athens Center Analysis
Deep analysis using our 100% verified authentic dataset with multi-agent intelligence
"""
import json
import sys
import logging
from pathlib import Path
from datetime import datetime
from typing import List, Dict, Optional, Tuple
import statistics
# ... | Python | 1 |
![&any], tvec!())
.unwrap();
assert_eq!(
input_facts,
tvec![
InferenceFact::default()
.with_datum_type(DatumType::F32)
.with_shape(shapefactoid![..]),
begin,
end,
strides,
... | Rust | 0 |
cantidad = int (input("ingrese la cantidad de productos: "))
precion =float (input("ingrese el precio: "))
pagar=cantidad*precion
if (cantidad >= 10 and cantidad <=20):
descuento=pagar*0.80
final=pagar-descuento
print("el total a pagar es: ",final)
elif (cantidad >= 10):
descuento=pagar*0.30
fina... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.