text string | label_name string | labels int64 |
|---|---|---|
class Product:
def __init__(self , price):
self._price = price
@property
def price(self):
return self._price
@price.setter
def price(self , new_price):
if new_price > 0 and type(new_price) == int:
self._price = new_price
@price.deleter
def price(sel... | Python | 1 |
MPCDROMCOLLECTION_GETBYDRIVESPECIFIER: u32 = 303u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCDROMCOLLECTION_ITEM: u32 = 302u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCDROMCOLLECTION_STARTMONITORINGCDROMS: u32 = 304u32;
#[doc = "*Requ... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
# 设置matplotlib支持中文显示
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
def time_integration_forward(u0, c, dx, dt, nsteps):
"""
显式前向差分(时间)+ 中心差分(空间)积分一维线性平流方程
∂u/∂t + c ∂u/∂x = 0
边界条件:固... | Python | 1 |
s(features)
g = expf.jacobian(ps[k])
assert np.allclose(g, jacobian_f[k])
@pytest.mark.parametrize("dim", range(2, 5))
class TestExp:
"""Tests for the callable class ``strawberryfields.apps.train.embed.Exp``"""
def test_zero_params(self, dim):
"""Tests that weights are equal to one wh... | Python | 1 |
::signal::ctrl_c() => return Ok(()),
}
}
}
async fn handle_request(
services: Arc<RwLock<Registry>>,
up: TcpStream,
mut connection: rustls::ServerConnection,
) {
let mut buf = [0; 1024];
let services = services.read();
// Peek into the 1 M... | Rust | 0 |
low capacity!",self.name)}).to_string();
return formatted;
}
else{
let formatted = json!({"current_distance":current_distance.to_string(),
"status":"alert_not_present"}).to_string();
return formatted;
}
}
}use crate::date_time::ZERO_NANOSECOND... | Rust | 0 |
import pandas as pd
from rdflib import Graph, Literal, Namespace, RDF, URIRef
from rdflib.namespace import XSD
import sys
def main(inputpath):
g = Graph()
ex = Namespace("http://schema.org/eicu")
eicu = Namespace("http://www.eicu.org/ontologies#")
g.bind("ex", ex)
g.bind("eicu", eicu)
# pastHis... | Python | 1 |
];
x_buffer.extend_from_slice(&vec_x);
vec_x = x_buffer
}
if vec_y.len() < COORDINATE_SIZE {
// pad
let mut y_buffer = vec![0; COORDINATE_SIZE - vec_y.len()];
y_buffer.extend_from_slice(&vec_y);
vec_y = y_buffer
}
l... | Rust | 0 |
let mut mmu = ExampleMem::new_with_data(prog);
let mut cpu = Cpu::new();
cpu.reg_set(Mode::User, reg::PC, 0x00);
cpu.reg_set(Mode::User, reg::CPSR, 0x10);
while cpu.step(&mut mmu) {}
for &(addr, val) in ($mem_checks).iter(... | Rust | 0 |
e), outputs=[confirm_reset_job_modal])
cancel_pause_job_btn.click(lambda: gr.update(visible=False), outputs=[confirm_pause_job_modal])
cancel_resume_job_btn.click(lambda: gr.update(visible=False), outputs=[confirm_resume_job_modal])
cancel_export_btn.click(lambda: gr.update(visible=False), outpu... | Python | 1 |
type) -> str:
"""
Return the unit str corresponding to the dtype's resolution.
Parameters
----------
dtype : DatetimeTZDtype or np.dtype
If np.dtype, we assume it is a datetime64 dtype.
Returns
-------
str
"""
if isinstance(dtype, DatetimeTZDtype):
return dtype.... | Python | 1 |
" the policy's condition"]
pub with_check: *mut Node,
}
#[test]
fn bindgen_test_layout_CreatePolicyStmt() {
assert_eq!(
::std::mem::size_of::<CreatePolicyStmt>(),
64usize,
concat!("Size of: ", stringify!(CreatePolicyStmt))
);
assert_eq!(
::std::mem::align_of::<CreatePoli... | Rust | 0 |
.set_external_reader_path(&replica_path).unwrap();
}
}
(data, tree)
} else {
(
data,
MerkleTreeWrapper::try_from_iter(elements.iter().map(|v| Ok(*v))).unwrap(),
)
}
}
fn generate_sub_tree<R: rand::Rng, Tree: MerkleTreeTrait>(
rng: &mut R,... | Rust | 0 |
from unittest.mock import MagicMock
import briefcase.console
from briefcase.console import NotDeadYet
def test_update(capsys, monkeypatch, dummy_console):
"""The message is only printed once for each interval."""
# initialization will set interval to 0 + 10
# update() will see time either at 5 or 15 and ... | Python | 1 |
import torch
class TriangularCausalMask():
def __init__(self, B, L, device="cpu"):
mask_shape = [B, 1, L, L]
with torch.no_grad():
self._mask = torch.triu(torch.ones(mask_shape, dtype=torch.bool), diagonal=1).to(device)
@property
def mask(self):
return self._mask
cla... | Python | 1 |
lags::REPE_PREFIX | CodeFlags::REPNE_PREFIX)
}
#[cfg(feature = "decoder")]
#[inline]
pub(crate) fn internal_clear_has_repe_prefix(this: &mut Instruction) {
this.code_flags &= !CodeFlags::REPE_PREFIX
}
#[cfg(any(feature = "decoder", feature = "encoder"))]
#[inline]
pub(crate) fn internal_set_has_repne_prefix(this: &m... | Rust | 0 |
from m4.sourcing.data_collection.processors import DOMTreeSimplificator
html_str = """<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
Blabla
</script>
<weird tag><another weird tag></another weird tag></weird tag>
<div1>
<a href="">Hello</a> Wo... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
MACDFS指标计算模块
用于计算分时MACD指标(MACDFS),专门用于一进二低吸战法的技术指标计算。
"""
import pandas as pd
import numpy as np
def calculate_ema_with_init(prices, period, init_value=None):
"""
计算指数移动平均线(EMA),支持自定义初始值
Args:
prices (pandas.Series): 价格序列数据
period (i... | Python | 1 |
ont-size: 1rem;
-webkit-appearance: none;
"#,
height = &self.props.height,
width = &self.props.width,
);
if self.invalid {
style_string.push_str(
r#"
border-color: rgb(238, 82, 26);
box-shadow: 0 0 ... | Rust | 0 |
point for the frame consumer. Subscribes to Kafka, sends frames to gRPC,
logs predictions and latency, and exposes Prometheus metrics.
"""
parser = argparse.ArgumentParser(description="Kafka → gRPC inference consumer")
parser.add_argument("--bootstrap", default="localhost:9092",
... | Python | 1 |
"Write proxy for field `MUX_CSX2`"]
pub struct MUX_CSX2_W<'a> {
w: &'a mut W,
}
impl<'a> MUX_CSX2_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MUX_CSX2_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "NOR/... | Rust | 0 |
url = url::url_with_fragment(url, fragment);
assert_eq!(&assembled_url, "https://localhost.localdomain/path/#test");
}
#[test]
fn url_with_fragment_empty_url() {
let url = "https://localhost.localdomain/path/";
let fragment = "";
let assembled_url = url::url_with_fragment(ur... | Rust | 0 |
"""
dependencies
llama.cpp (https://github.com/ggerganov/llama.cpp)
llama-cpp-python (https://github.com/abetlen/llama-cpp-python)
llama.cpp
1. 通过llama.cpp将模型转换为ggml格式
2. 参考llama.cpp对转换后的模型量化到 (q4_0, q4_1, q5_0, q5_1, q8_0)
- 在转换过程中会遇到tokenizer对不齐的问题,自行在词表中添加相应个数token即可
... | Python | 1 |
_UNORDERED_ACCESS_VIEW = 8,
}}
STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC_VertexBuffer {
Slot: UINT,
}}
STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC_Constant {
RootParameterIndex: UINT,
DestOffsetIn32BitValues: UINT,
Num32BitValuesToSet: UINT,
}}
STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC_ConstantBuffe... | Rust | 0 |
if item.name is not None:
types[item.name] = self.visit(item)
else:
roots.append(self.visit(item))
for union in unions:
types[union.name] = self.visit(union)
for interface in interfaces:
types[interface.name] = self.visit(interface)
... | Python | 1 |
ze_before=False,只执行forward_post
if self.normalize_before:
return self.forward_pre(tgt, memory, tgt_mask, memory_mask,
tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos)
return self.forward_post(tgt, memory, tgt_mask, memory_mask,
... | Python | 1 |
# решение коллизий квадратичным пробированием
def insert():
while True: # цикл для добавления значений
input_value = input('Введите значение для добавления в таблицу или "стоп" для окончания добавлений: ')
if input_value != 'стоп':
values_list = [] # список для хранения значений, добав... | Python | 1 |
ked_store.insert_transcript_data(dkg_id, pub_coeffs(), BTreeMap::new());
locked_store.insert_individual_public_key(dkg_id, node_id, public_key);
}
threshold_sig_data_store
}
fn indices(mappings: Vec<(NodeId, NodeIndex)>) -> BTreeMap<NodeId, NodeIndex> {
btree_map(mappings)
}
fn btree_map<H>(entrie... | Rust | 0 |
IST;
pub const FLAG_BOXED: usize = constants::FLAG_BOXED;
pub const FLAG_LITERAL: usize = constants::FLAG_LITERAL;
pub const FLAG_IMMEDIATE: usize = constants::FLAG_IMMEDIATE;
pub const FLAG_IMMEDIATE2: usize = constants::FLAG_IMMEDIATE2;
// First class immediates
pub const FLAG_PID: usize = co... | Rust | 0 |
_INVALID_KEY_FORMAT: HRESULT = 0x80310034u32 as HRESULT;
pub const FVE_E_INVALID_PASSWORD_FORMAT: HRESULT = 0x80310035u32 as HRESULT;
pub const FVE_E_FIPS_RNG_CHECK_FAILED: HRESULT = 0x80310036u32 as HRESULT;
pub const FVE_E_FIPS_PREVENTS_RECOVERY_PASSWORD: HRESULT = 0x80310037u32 as HRESULT;
pub const FVE_E_FIPS_PREVE... | Rust | 0 |
from escrever_devagar import escrever_devagar
def subir_de_nivel(personagem):
while personagem["exp"] >= personagem["exp_necessaria"]:
personagem["exp"] -= personagem["exp_necessaria"]
personagem["nivel"] += 1
escrever_devagar(f"Você subiu para o nível {personagem['nivel']}!")
... | Python | 1 |
if step % 5 == 0:
reward_avg += evaluate_policy(agent_pre_train)
if step % 100 == 0:
print(reward_avg / 20, step, agent_pre_train.num_timesteps)
reward_avg = 0.0
agent_supervised = DDPG("MlpPolicy", env=xietong_bu0_env(), gamma=0.98, action_noise=action_noise, policy_kwargs=policy_kwargs, ... | Python | 1 |
.service(Box::new(service_gen))
.fidl_interfaces(&[Interface::Display(display::InterfaceFlags::LIGHT_SENSOR)])
.spawn_and_get_nested_environment(ENV_NAME)
.await
.unwrap();
let display_service = env.connect_to_protocol::<DisplayMarker>().unwrap();
let data = display_service... | Rust | 0 |
(1,)* (self.enforce_dim - res_dim))
# Estimate estimates after predict, so if something goes
# wrong, above exception handling occurs
if self.ca.is_enabled('probabilities'):
if hasattr(self._skl_learner, 'predict_proba'):
# Duplication of computation, since in many s... | Python | 1 |
use usx_book_codes::usx_book_code;
use thiserror::Error;
use usx_book_codes::usx_code_to_book;
#[derive(Error, Debug)]
pub enum UsxError {
#[error("book not found in this translation")]
BookNotFound(Book),
#[error("citations that span multiple books are not supported")]
CrossBookCitation,
#[error... | Rust | 0 |
'''
Escriba las instrucciones que permitan ordenar una cadena
de caracteres en orden alfabético ascendente. Para probar,
vamos a tomar la cadena c = "francia".
El programa debe devolver "aacfinr"
'''
c = "francia"
c_asc = ("".join (sorted(c)))
print (c_asc) | Python | 1 |
#[doc(alias = "GMIME_FILTER_BEST_ENCODING")]
const ENCODING = ffi::GMIME_FILTER_BEST_ENCODING as u32;
}
}
impl fmt::Display for FilterBestFlags {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
<Self as fmt::Debug>::fmt(self, f)
}
}
#[doc(hidden)]
impl IntoGlib for FilterBes... | Rust | 0 |
gid = token_urlsafe(12)
out_pah = await VidEcxecutor(self, self.link, gid, metadata).execute()
if not out_pah:
return
if not await aiopath.exists(str(out_pah)):
self.name = self.vidMode[1] or self.name
await self.onUploadError('No file(s) to upload')
... | Python | 1 |
token = "7061303481:AAFn1wjy2lzFvoKC4Wtb7-UNh4xNytxKNrs" | Python | 1 |
an incoming connection
fn check_incoming(&mut self) -> Result<Option<Box<dyn Socket>>, ()>;
/// Check for connection errors
fn check_err(&mut self) -> Result<(), ()>;
/// Close the listener (deny new connections)
fn close(&mut self) -> Result<(), ()>;
}
/// TCP listener
pub struct ListenerTcp {
... | Rust | 0 |
ild_storage::<Test>()
.unwrap()
.into()
}
pub fn run_to_block(n: u64) {
while System::block_number() < n {
if System::block_number() > 1 {
System::on_finalize(System::block_number());
}
System::set_block_number(System::block_number() + 1);
System::on_initialize(System::block_number());
Timestamp::set... | Rust | 0 |
=> Err(ShellError::UnsupportedInput(
"Input data is not supported by this command.".to_string(),
Span::unknown(),
)),
}
}
fn format_record(
format_operations: &[FormatOperation],
data_as_value: &Value,
) -> Result<String, ShellError> {
let mut output = String::new();
... | Rust | 0 |
}
let web3 = create_web3(chain.unwrap());
// CAVEAT: we cannot do early check whether the input address is indeed
// a contract address, but until we get response of bytecode of back.
//
// If it is contract address -> we will get lengthy of bytecode string
// If it is EOA address -> emp... | Rust | 0 |
if not client_data:
data = {
"window_start": current_window_start,
"current_count": 0,
"prev_count": 0
}
w_count = 0
overlap = 0
self.storage.add_client(client_id, data)... | Python | 1 |
from typing import Annotated, Union
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app import crud
from app.core.deps import get_current_user
from app.core.exception import MultiLangHTTPExceptions
from app.database.database impor... | Python | 1 |
_special_tokens=True)
# decoded_labels = processor.batch_decode(labels, skip_special_tokens=True)
# # decoded_preds = processor.tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
# # decoded_labels = processor.tokenizer.batch_decode... | Python | 1 |
[structopt(short = "c", long = "no-color")]
color: bool,
}
#[tokio::main]
async fn main() {
let args = Opt::from_args();
let out = output::Preferences {
color_enabled: !args.color,
};
out.logo();
out.version();
if args.driver {
out.driver();
} else {
monitor(!... | Rust | 0 |
Error> {
let pubkey = alloc_c_string(&self.to_hex())?;
let mut handle = ErrorHandle::new()?;
let mut compressed_pubkey: *mut c_char = ptr::null_mut();
let error_code =
unsafe { CfdCompressPubkey(handle.as_handle(), pubkey.as_ptr(), &mut compressed_pubkey) };
let result = match error_code {
... | Rust | 0 |
# color += (rgb[3],) # Add in Alpha
draw.point((led_pos, 0), fill=color)
#
# LED sequence examples
#
def cycle_colors(colors=("red", "green", "blue"), delay_secs=1):
"""
Cycle a set of colours.
"""
set_color('black') # Start with all LED's "off"
for c in colors:
pri... | Python | 1 |
?;
} else {
msg.reply(
ctx,
format!(
"Could not find project version build (Project: {}, Version: {}, Build: {})",
&project_name, &version, &build
),
)
.await?;
}
Ok(())
}
<filename>crates/starlight/src/runtime/stri... | Rust | 0 |
onId, SessionKey};
use dftk_common::models::speaker::SpeakerKey;
use dftk_database::sessions::{SessionDocument, SessionPatch};
use dftk_database::{Repositories, SynchronizeResult};
use dftk_hugo_site::site_writer::GenerateResult;
use crate::graphql::categories::CategoryOutputType;
use crate::graphql::formats::FormatOu... | Rust | 0 |
= (
"m5 exit;"
+ "echo 'This is running on Timing CPU cores.';"
+ "sleep 1;"
+ "m5 exit;"
)
workload = obtain_resource("x86-ubuntu-18.04-boot")
workload.set_parameter("readfile_contents", command)
board.set_workload(workload)
simulator = Simulator(
board=board,
on_exit_event={
# Here w... | Python | 1 |
ntityEscaper(codepoint2name, name2codepoint)
html_entities_escape = _html_entities_escaper.escape_entities
html_entities_unescape = _html_entities_escaper.unescape
def htmlentityreplace_errors(ex):
"""An encoding error handler.
This python `codecs`_ error handler replaces unencodable
characters with HTM... | Python | 1 |
from tensorflow.keras.layers import Dropout
# Use the VAE encoder to project the small training set into the latent space
small_x_train_encoded, _ = conv_encoder.predict(small_x_train, batch_size=100)
# Define a small MLP that takes the 2D vectors as input.
inp = x = Input(shape=(latent_dim,))
x = Dense(256, activati... | Python | 1 |
from __future__ import absolute_import, division, print_function, unicode_literals
from gratipay.testing import Harness
class Tests(Harness):
def test_distributing_redirects_when_no_money_is_available(self):
self.make_team()
assert self.client.GxT('/TheEnterprise/distributing/').code == 302
... | Python | 1 |
import numpy as np
class Environment:
@staticmethod
def get_aic(real_conf, pred_conf, num_params=0):
pred_conf = pred_conf.where(pred_conf != 1, 1 - (10 ** -10))
pred_conf = pred_conf.where(pred_conf != 0, 0 + (10 ** -10))
ll = (real_conf * np.log(pred_conf) + (1 - real_conf) * (np.log(... | Python | 1 |
import torch
from diffusers import LTXImageToVideoPipeline
from diffusers.utils import export_to_video, load_image
# Set device and dtype
device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float16
print(f"Using device: {device}")
# Load the LTXImageToVideoPipeline from the Lightricks/LTX-Video chec... | Python | 1 |
from syzscope.interface.s2e import S2EInterface
s2e_path = '/home/xzou017/projects/KOOBE-test/s2e'
kernel_path = '/home/xzou017/projects/KOOBE-test/s2e/images/debian-9.2.1-x86_64-0e2adab6/guestfs/vmlinux'
syz_path = '/home/xzou017/projects/SyzbotAnalyzer/tools/gopath/src/github.com/google/syzkaller'
s2e_project_path =... | Python | 1 |
#!/usr/bin/env python
# CiderPress: Machine-learning based density functional theory calculations
# Copyright (C) 2024 The President and Fellows of Harvard College
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free S... | Python | 1 |
######");
}
let nreplicats = 100 / bodies.len();
for rb in bodies.iter() {
for _ in 0 .. nreplicats {
let mut rb = rb.clone();
let pos = random::<Vec3<f32>>() * 30.0+ Vec3::new(-15.0, 15.0, -15.0);
rb.append_translation(&pos);
world.add_body(rb);
... | Rust | 0 |
!("IF LET: x (from b) = {}. x is of type &&Rect.", x);
}
// Trying to use & in this case works, we get rid of one of the references.
let b = a.as_ref();
if let Some(&x) = b {
}
}
fn demo_as_mut() {
println!(">>> demo_as_mut (not sure what is going on here, to be honest)");
let r = Rect::de... | Rust | 0 |
""" script to test Bokeh server """
from random import random
import bokeh
from bokeh.layouts import column
from bokeh.models import Button
from bokeh.palettes import RdYlBu3
from bokeh.plotting import figure, curdoc
# create a plot and style its properties
p = figure(x_range=(0, 100), y_range=(0, 100), toolbar_loc... | Python | 1 |
urls = [line.strip() for line in f if "?" in line and "=" in line]
filtered_urls = [url for url in urls if url.startswith("http")]
with open(output, "w") as out:
for url in filtered_urls:
out.write(url + "\n")
print(Fore.YELLOW + f"[✓] Filtered {len(filtered_urls)} potential SQLi... | Python | 1 |
2_index = dimension2_indexes[position[1]]
print(position, value, dimension1_index, dimension2_index)
image[dimension1_index, dimension2_index] = value
print(image)
fig, ax = plt.subplots()
img = ax.imshow(
image,
extent=[
dimens... | Python | 1 |
#
# Test Routines for the bot
#
import time
from inventory import *
def wieldTest(pybot):
delay_t = 0.0
pybot.printInventory()
print('-- Static tests')
print(f'Stone Pickaxe: {pybot.mcData.itemsByName.stone_pickaxe.id}')
print(f'Stone Axe: {pybot.mcData.itemsByName.stone_axe.id}')
print... | Python | 1 |
.exists()
def test_custom_commands_functionality(self):
"""Test custom commands plugin functionality."""
# Import the plugin module directly
from custom_commands.plugin import CustomCommandsPlugin
plugin = CustomCommandsPlugin()
assert plugin.name == "custom_com... | Python | 1 |
value } in test_pairs_updated.iter().cloned() {
assert_eq!(
Some(value),
updated_checkout.read(correlation_id, &key).unwrap()
);
}
}
#[test]
fn commit_updates_state_and_original_state_stays_intact() {
let correlation_id = CorrelationI... | Rust | 0 |
or Os {
}
impl ::protobuf::reflect::ProtobufValue for Os {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Enum(self.descriptor())
}
}
#[derive(Clone,PartialEq,Eq,Debug,Hash)]
pub enum AccountType {
Spotify = 0,
Facebook = 1,
}
impl ::protobu... | Rust | 0 |
/// Returns fence used for image acquisition for swapchain.
pub fn get_acquire_fence(&self) -> vk::Fence {
self.acquire_fence
}
/// Waits for the image and its associated objects to be ready to be written
/// to.
pub fn wait_for_acquire_fence(&self) -> SarektResult<()> {
unsafe {
Ok(
se... | Rust | 0 |
tablelineStartup,
"pmoabCfglineEdfaLaserCtrl": pmoabCfglineEdfaLaserCtrl,
"pmoabCfglineEdfaLaserMode": pmoabCfglineEdfaLaserMode,
"pmoabCfgLabels": pmoabCfgLabels,
"pmoabCfgLabelclientTable": pmoabCfgLabelclientTable,
"pmoabCfgLabelclientEntry": pmoabCfgLabelclientEntry,
"pmoab... | Python | 1 |
})?;
writeln!(&private_key_file, "{}", private_key.as_hex()).map_err(|err| {
CliError::ActionError(format!(
"Failed to write to private key file '{}': {}",
private_key_path.display(),
err
))
})?;
}
{
if public_key_... | Rust | 0 |
e too large detections
if detect_xyxy[2] - detect_xyxy[0] > 0.8 * w and detect_xyxy[3] - detect_xyxy[1] > 0.8 * h:
continue
if detect_object == constants.YELLOW_POINTS and (detect_xyxy[2] - detect_xyxy[0] > 0.1 * w or detect_xyxy[3] - detect_xyxy[1] > 0.1 * h):
detect_object = c... | Python | 1 |
from hearthbreaker.cards.base import HeroCard
from hearthbreaker.constants import CHARACTER_CLASS, MINION_TYPE
from hearthbreaker.powers import MagePower, DruidPower, HunterPower, PaladinPower, PriestPower, RoguePower,\
ShamanPower, WarlockPower, WarriorPower, JaraxxusPower, DieInsect
class Malfurion(HeroCard):
... | Python | 1 |
__all__ = [
'OnnxRound',
]
import torch
from torch import nn
from onnx2torch.node_converters.registry import add_converter
from onnx2torch.onnx_graph import OnnxGraph
from onnx2torch.onnx_node import OnnxNode
from onnx2torch.utils.common import OnnxToTorchModule
from onnx2torch.utils.common import OperationConver... | Python | 1 |
}
for tx in transactions
]
return Response(
{"jsonrpc": "2.0", "id": rpc_id, "result": {"statements": statements}}
)
def get_information(self, params, rpc_id):
"""
get information method process
"""
info_fields = ("id",)
a... | Python | 1 |
import tensorflow as tf
#tf.compat.v1.disable_eager_execution()
def sink(a, b, M, m_size, reg, numItermax=1000, stopThr=1e-9):
# we assume that no distances are null except those of the diagonal of distances
# a = tf.expand_dims(tf.ones(shape=(m_size[0],)) / m_size[0], axis=1) # (na, 1)
# b = tf.expand_d... | Python | 1 |
r.dense.bias"] = torch.tensor(pretrained_model_params["encoder"]["pooler"]["bias"])
# Masked LM Layers
new_state_dict["cls.predictions.transform.dense.weight"] = torch.tensor(
pretrained_model_params["predictions_dense"]["kernel"]
).T
new_state_dict["cls.predictions.transform.dense.bias"] = tor... | Python | 1 |
tterns: EnemyMovementPatterns
enemy_sprites: EnemySprites
exp_modifier: ExpModifier
final_floor: FinalFloor
gear_variety_after_b9: GearVarietyAfterB9
goal: Goal
gold_modifier: GoldModifier
healing_floor_chance: HealingFloorChance
inactive_exp_gain: InactiveExpGain
initial_floor: Init... | Python | 1 |
start=None):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
if isinstance(path, bytes):
curdir = b'.'
sep = b'/'
pardir = b'..'
else:
curdir = '.'
sep = '/'
pardir = '..'
if start is None:
... | Python | 1 |
on_times': {
'water': TAU_THERMAL_WATER,
'air': TAU_THERMAL_AIR,
'coffee': TAU_THERMAL_COFFEE
},
'cfl_numbers': {
'water': CFL_THERMAL_WATER,
'air': CFL_THERMAL_AIR,
'coffee': CFL_THERMAL_COFFEE
},
'thermal_propertie... | Python | 1 |
address : Wrapper<(hdwallet::XPrv, address::ExtendedAddr)> = Arbitrary::arbitrary(g);
let value : Wrapper<coin::Coin> = Arbitrary::arbitrary(g);
let (xprv, address) = address.unwrap();
Wrapper(
(xprv,
tx::TxOut {
address: address,
... | Rust | 0 |
# RSI + 均线 联合策略
# 兼顾趋势和震荡
# 均线(MA)捕捉的是趋势、方向性行情,RSI则擅长判断超买/超卖、震荡区间。
# 两者联合,可以过滤掉趋势中的虚假震荡信号,也能防止趋势追高/杀跌。
import backtrader as bt
class MaRsiStrategy(bt.Strategy):
params = (
('ma_period', 20),
('rsi_period', 14),
('rsi_buy', 40),
('rsi_sell', 60),
)
def __init__(self):
... | Python | 1 |
# -*- encoding: utf-8 -*-
#
# Copyright P. Christeas <p_christ@hol.gr> 2008,2009
# Copyright OpenERP SA. (http://www.openerp.com) 2010
#
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its e... | Python | 1 |
import torch
t = torch.ones((2,3))
t_0 = torch.cat([t,t], dim=0)
t_1 = torch.cat([t,t], dim=1)
t = torch.cat()
print('t_0:{} shape:{}\nt_1:{} shape:{}'.format(t_0,t_0.shape,t_1,t_1.shape)) | Python | 1 |
import pathlib
import click
import librosa
import matplotlib.pyplot as plt
import numpy as np
import parselmouth as pm
import tqdm
from textgrid import TextGrid
import distribution
@click.command(help='Generate word-level pitch summary')
@click.option('--wavs', required=True, help='Path to the segments directory')
... | Python | 1 |
version,
status: Status::Enabled as i32,
mtime: Some(mtime),
footprint_id: Some(footprint.id),
digest: Some(&footprint.digest),
created_at: now,
updated_at: now,
},
)?;
info!("history created: {}: {}, {}", history.id, &history.path,... | Rust | 0 |
# Copyright 2021 The Couler Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | Python | 1 |
s_sys::core::PCSTR = 74i32 as _;
#[doc = "*Required features: `\"Win32_Security_Cryptography\"`*"]
pub const X509_ALTERNATE_NAME: ::windows_sys::core::PCSTR = 12i32 as _;
#[doc = "*Required features: `\"Win32_Security_Cryptography\"`*"]
pub const X509_ANY_STRING: i32 = 6i32;
#[doc = "*Required features: `\"Win32_Securi... | Rust | 0 |
"Base Size Error: size = {}", s),
}
}
}
impl error::Error for Error {}
/// `BigNum` for big number handling
/// - Using `Vec<u32>` for data and using `u32::max_value()` as base of the number
/// - Can handle negative numbers
///
/// # Examples
///
/// ```
/// use hyeong::big_number::BigNum;
///
/// // Wa... | Rust | 0 |
e
col = (x - self.left_margin) // self.square_size
#Verifica si el clic está dentro de los límites de la cuadrícula
if 0 <= row < self.rows and 0 <= col < self.cols:
if button == 1: #Si se presionó el botón izquierdo del ratón
if self.grid[row][col] == 0: #Si la ce... | Python | 1 |
doc = " \\begin{pmatrix}"]
#[doc = " \\exp(-i \\theta/2) & 0 \\\\"]
#[doc = " 0 & \\exp(i \\theta/2)"]
#[doc = " \\end{pmatrix}"]
#[doc = " \\f]"]
#[doc = " with circuit diagram:"]
#[doc = "\\f["]
#[doc = "\\begin{tikzpicture}[scale=.5]"]
#[doc = "\\node[draw=none] at (-3.5, 0) {rot};"]
... | Rust | 0 |
_id, &meta, 0, &test_rows)
.unwrap();
let mut search_keys: Vec<Vec<u8>> =
test_rows.iter().map(|row| row.search_key.clone()).collect();
// Try a random search key also and test that it is not found
let mut random_search_key = vec![0u8; search_keys[0].len()];
rng.fill_bytes(&mut random_... | Rust | 0 |
: u32 = 8u32;
#[doc = "*Required features: `\"Win32_Globalization\"`*"]
pub const CAL_SDAYNAME3: u32 = 9u32;
#[doc = "*Required features: `\"Win32_Globalization\"`*"]
pub const CAL_SDAYNAME4: u32 = 10u32;
#[doc = "*Required features: `\"Win32_Globalization\"`*"]
pub const CAL_SDAYNAME5: u32 = 11u32;
#[doc = "*Required ... | Rust | 0 |
tes<Bytes>>, Bytes>,
) -> Result<T, NetworkError>
where
T: Message,
TSubstream: AsyncRead + Unpin,
{
// Read from stream.
let data: Bytes = substream.next().await.map_or_else(
|| Err(io::Error::from(io::ErrorKind::UnexpectedEof)),
|data| Ok(data?.freeze()),
)?;
// Parse to messag... | Rust | 0 |
KeyType::EC => {
let key = match EllipticCurve::new(key_name) {
Ok(key) => key,
Err(_) => return Err(TxBuilderError::TxGenerateError(6001)),
};
Key::Ec(key)
}
};
let tx = Transacti... | Rust | 0 |
, _) = cx.qpath_res(path, cast_expr.hir_id)
{
span_lint(
cx,
CAST_ENUM_CONSTRUCTOR,
expr.span,
"cast of an enum tuple constructor to an integer",
);
}
}
<reponame>dodomorandi/nalgebra
use na::{Scalar, RealField, U3, DefaultAllocator};
use crate::t... | Rust | 0 |
b = torch.gather(
reward_sample,
2,
labels_sample.unsqueeze(-1)
).squeeze(2) # (bsize, N)
logprobs_sample = dist.log_prob(labels_sample.view(-1)).view(bsize, N) # (bsize, N)
# always calculate for monitoring purposes, however we can put inside if, if we want to monitor only sometimes
labels_argmax = l... | Python | 1 |
/// Piecewise Linear function in [0, 1] -> [0, 1].
#[derive(PartialEq, Eq, sp_core::RuntimeDebug)]
pub struct PiecewiseLinear<'a> {
/// Array of points. Must be in order from the lowest abscissas to the highest.
pub points: &'a [(Perbill, Perbill)],
/// The maximum value that can be returned.
pub maximum: Perbill,
... | Rust | 0 |
itmap_ptr_ptr }
}
}
}
pub fn get_surface_ptr(ptr: NodePtr) -> SurfacePtr {
ptr
}
pub fn get_control_ptrs(
cache: &ObjectCache,
block: BlockRef,
ptr: NodePtr,
control: usize,
) -> ControlPointers {
let block_layout = cache.block_layout(block).unwrap();
let control_offset = block... | Rust | 0 |
Mermaid Class Views\n```mermaid\n"
block += class_view.get_mermaid()
block += "\n```\n"
prompt_blocks.append(block)
block = "## Source Code\n```python\n"
block += source_code
block += "\n```\n"
prompt_blocks.append(block)
prompt = "\n---\n".join(prompt_blo... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.