text string | label_name string | labels int64 |
|---|---|---|
from init_apex_client import init_client
from send_order_apex import send_order_apex
import time
# 初始化客户端
client_apex = init_client()
configs = client_apex.configs()
# 获取用户和账户信息
client_apex.get_user()
client_apex.get_account()
# 发送一个市价买单
currentTime = time.time()
limitFeeRate = client_apex.account['takerFeeRate... | Python | 1 |
ption<usize> {
self.values.binary_search_by(|&(n, _)| n.cmp(&name)).ok()
}
/// Returns the value corresponding to the given name.
pub fn get(&self, name: Name) -> Option<&T> {
self.values.binary_search_by(|&(n, _)| n.cmp(&name))
.ok().map(|pos| &self.values[pos].1)
}
//... | Rust | 0 |
"""
chapter08/rpi/transistor_rpi.py
Using a Raspberry Pi & Python to control a MOSFET transistor.
Dependencies:
pip3 install pigpio
Built and tested with Python 3.11.22 on Raspberry Pi 5
"""
import pigpio
from time import sleep
GPIO = 21
pi = pigpio.pi()
# 8000 max hardware timed frequency by default pigpiod con... | Python | 1 |
# -*- coding: utf8 -*-
#!/usr/bin/env python
#
# Parts script module for socket strip footprints for KicCad
#
# This module is built on top of the kicad-footprint-generator framework
# by Thomas Pointhuber, https://github.com/pointhi/kicad-footprint-generator
#
# This module is free software: you can redistribute it a... | Python | 1 |
paused: false,
anchor_liquidation_queue: msg
.anchor_liquidation_queue
.unwrap_or_else(|| Addr::unchecked("terra1e25zllgag7j9xsun3me4stnye2pcg66234je3u")),
collateral_token: msg
.collateral_token
.unwrap_or_else(|| Addr::unchecked("terra1kc87mu460... | Rust | 0 |
import logging
import pytest
import pytest_asyncio
from typing import List, Optional
from biothings_typed_client.genes import GeneClient, GeneClientAsync, GeneResponse
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
@pytest.fixture
def sync_client():
"""Fixture providing a synchronous gene cli... | Python | 1 |
self.nodes[0].add_p2p_connection(TestNode(), services=NODE_NETWORK|NODE_WITNESS)
# self.old_node sets only NODE_NETWORK
self.old_node = self.nodes[0].add_p2p_connection(TestNode(), services=NODE_NETWORK)
# self.std_node is for testing node1 (fRequireStandard=true)
self.std_node = self.no... | Python | 1 |
((rtm)->errorStatus)
#endif
#ifndef rtmSetErrorStatus
# define rtmSetErrorStatus(rtm, val) ((rtm)->errorStatus = (val))
#endif
/* External inputs (root inport signals with default storage) */
typedef struct {
real_T M1_HP_D[84]; /* '<Root>/M1_HP_D' */
real_T M1_HP_cmd[42]; ... | Rust | 0 |
.unwrap();
let root = doc.root_element();
assert!(Restriction::parse(root).is_err());
}
}
use std::fs::File;
use std::io::prelude::*;
use serde::de::{DeserializeOwned};
use errors::*;
use toml;
pub fn from_file<T>(mut f: File) -> Result<T>
where T: DeserializeOwned
{
let m... | Rust | 0 |
label_car_start_postion_len\
, label_car_start_postion_wid + label_width, label_car_start_postion_len + label_length,\
label_length +label_car_start_postion_wid + label_width*2))
self.label_current_position.setObjectName("label_order_num")
self.label_current_position.setText(... | Python | 1 |
(input, chunk) = snd2_chunk(input)?;
Ok((input, chunk))
}
fn all_snd2_chunks(input: &[u8]) -> IResult<&[u8], Vec<SND2Chunk>> {
let (input, chunks) = many0(next_snd2_chunk)(input)?;
Ok((input, chunks))
}
fn main() {
let mut args = std::env::args();
if args.len() != 2 {
println!("usage: {}... | Rust | 0 |
from typing import Literal, Optional, cast
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import create_hogql_database
from posthog.hogql.errors import NotImplementedError, QueryError, SyntaxError
from posthog.hogql.parser import parse_expr
from postho... | Python | 1 |
ed::parse_terminated(input)?;
Ok((s, args))
}
pub fn parse_args(tokens: TokenStream) -> Result<(LitStr, Punctuated<Expr, Comma>)> {
SynParser::parse2(args, tokens)
}
fn sargs(input: ParseStream) -> Result<(Expr, LitStr, Punctuated<Expr, Comma>)> {
let s: Expr = input.parse()?;
let _: Comma = input.pa... | Rust | 0 |
#!/usr/bin/python3
#Criação de script com python do curso da Cod3r.com na Udemy
#para validar numeros escolhidos e sorteados na Lotomania de 1 a 50
#aluno: Adriel Silva Camargos
from random import randint
#Sorteando 50 números de 0 a 99
#numero_preenchido = 1
#minha_cartela = []
#cartela in range (1, 100):
#resulta... | Python | 1 |
e state schema,
# please also update the cache key with a version number.
cache_key = f"polar:customer_state:v3:{customer.id}"
if cache:
raw_state = await redis.get(cache_key)
if raw_state is not None:
return CustomerState.model_validate_json(raw_state)
... | Python | 1 |
(), "SHIFT", "Shift"),
(Self::LOCK.0.into(), "LOCK", "Lock"),
(Self::CONTROL.0.into(), "CONTROL", "Control"),
(Self::MOD1.0.into(), "MOD1", "Mod1"),
(Self::MOD2.0.into(), "MOD2", "Mod2"),
(Self::MOD3.0.into(), "MOD3", "Mod3"),
(Self::MOD4.0.into(),... | Rust | 0 |
nr': 'सिंधी', 'yi': 'סינדהי', 'yo': 'Èdè Sindhi', 'yrl': 'sĩdi', 'yue': '信德文', 'yue-Hans': '信德文', 'yue-Hant': '信德文', 'zh': '信德语', 'zh-Hans': '信德语', 'zh-Hant': '信德文', 'zu': 'isi-Sindhi'},
'sda': {'en': "Toraja-Sa'dan"},
'sdb': {'en': 'Shabak'},
'sdc': {'ast': 'sardu sassarés', 'br': 'sasareseg', 'ca': 'sasse... | Python | 1 |
import numpy as np
import pyfits as pf
import sys, glob
from Neutral_density import *
def primary_flux(wdir,pattern):
for i,allfiles in enumerate(glob.iglob(pattern+"*")):
if i==0:
image_filename=allfiles
else:
print("Warning more than one file found with this pattern name. Used the first one:",image_filena... | Python | 1 |
red_take<T>(value: Shared<T>) -> T {
shared_try_take(value).map_err(|_| ()).unwrap()
}
/// Arguments to a function call, which is a list of [`&mut Dynamic`][Dynamic].
pub type FnCallArgs<'a> = [&'a mut Dynamic];
/// A general function pointer, which may carry additional (i.e. curried) argument values
/// to be pa... | Rust | 0 |
"""
Write a function to convert a given string to a tuple of characters.
assert string_to_tuple("python 3.0")==('p', 'y', 't', 'h', 'o', 'n', '3', '.', '0')
"""
def string_to_tuple(string):
"""
Converts a string to a tuple of characters.
"""
return tuple(string)
# Test
assert string_to_tuple("python 3... | Python | 1 |
/whatwg/html/issues/3518#issuecomment-644581962
AsciiPrintable | Unicode => ASCII_RANGE.collect(),
Custom(custom) => custom.clone(),
}
}
}
/// The various parsed password rules
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PasswordRules {
/// The maximum length of c... | Rust | 0 |
nst _ as usize },
// 40usize,
// concat!(
// "Offset of field: ",
// stringify!(_xmlURI),
// "::",
// stringify!(port)
// )
// );
// assert_eq!(
// unsafe { &(*(::std::ptr::null::<_xmlURI>())).path as *const _ as usize },
// 48usize,
// concat!(
// "Offset of fi... | Rust | 0 |
_url: &String) -> Result<Vec<ForecastPeriod>, reqwest::Error> {
let forecast_resp = reqwest::Client::new()
.get(request_url)
.header(reqwest::header::USER_AGENT, "<EMAIL>")
.header("Feature-Flags", thread_rng().gen_range(100..1000))
.send()
.await?
.text()
.aw... | Rust | 0 |
expected_size);
let position = position.max(ctx.input().screen_rect().left_top());
position
} else if ctx.memory().everything_is_visible() {
Pos2::default()
} else {
return; // No good place for a tooltip :(
};
// TODO: default size
let id = Id::tooltip();
let ... | Rust | 0 |
eld bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | ((value as u32 & 0x01) << 13);
self.w
... | Rust | 0 |
else:
meanMelLoss = meanMelLoss * 0.99 + 0.01 * melLoss.item()
meanVelocityMSELoss = (
meanVelocityMSELoss * 0.99
+ 0.01 * velocityMSELoss.sqrt().item()
)
meanSTFTLoss = meanSTFTLoss * 0.99 + 0.01 * STFTLoss... | Python | 1 |
let mut generic_types = quote!();
for item in items {
if let ImplItem::Method(method) = item {
if let Visibility::Public(vis) = method.vis {
let generics = method.sig.generics;
generic_types.extend(quote!(#generics));
}
}
}
// prin... | Rust | 0 |
1
},
);
ctx.set(t, Stat::castele, etg::Earth);
ctx.set(t, Stat::casts, 0);
}
Self::siphon | Self::v_siphon => {
if throttle(ctx, c) {
let owner = ctx.get_owner(c);
let foe = ctx.get_foe(owner);
if !ctx.sanctified(foe) && ctx.spend(foe, etg::Chroma, 1) {
ctx.fx(c, Fx::Quan... | Rust | 0 |
from Py4GWCoreLib.enums import outpost_name_to_id, explorable_name_to_id
# 1) IDs
_2_zendaijunoutpost_to_haijulagoon_ids = {
"outpost_id": 213,
}
# 2) Outpost exit path
_2_zendaijunoutpost_to_haijulagoon_outpost_path = [
(18255, 11594),
(18729, 12534),
(18982, 13543),
(19225, 14513),
]
# 3) Segme... | Python | 1 |
ent() {
let mut index = DeletedIndex::new();
let mut world = World::new();
let entity = world.spawn((1i32, "hello".to_owned()));
index.update(world.query::<(&i32, &String)>().iter());
world.remove_one::<String>(entity).unwrap();
assert_eq!(
index.update(worl... | Rust | 0 |
)
_describe -t commands 'my_app commands' commands "$@"
}
(( $+functions[_my_app__help_commands] )) ||
_my_app__help_commands() {
local commands; commands=()
_describe -t commands 'my_app help commands' commands "$@"
}
(( $+functions[_my_app__some-cmd-with-hypens_commands] )) ||
_my_app__some-cmd-with-h... | Rust | 0 |
use eth_encode_packed::ethabi::ethereum_types::{U256, Address};
/// // Uint24
/// SolidityDataType::NumberWithShift(U256::from(3838), TakeLastXBytes(24));
/// // String
/// SolidityDataType::String("ipfs-cid-url-very-long");
/// // Bool
/// SolidityDataType::Bool(true);
/// // Address
/// use std::convert::TryInto;
//... | Rust | 0 |
not found.").into())
}
pub fn lists() -> FieldResult<ListConnection> {
let agent_info = agent_info()?;
let agent_address: AnyDhtHash = agent_info.agent_initial_pubkey.clone().into();
let list_links = get_links(agent_address.into(), Some(utils::link_tag("list")?))?
.into_inner()
.into_iter... | Rust | 0 |
import os
import logging
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from sqlalchemy.orm import DeclarativeBase
from werkzeug.middleware.proxy_fix import ProxyFix
# Configure logging
logging.basicConfig(level=logging.DEBUG)
class... | Python | 1 |
points to a real function, false if points to a `panic!` fn.
is_loaded: bool,
}
impl FnPtr {
/// Creates a `FnPtr` from a load attempt.
fn new(ptr: *const __gl_imports::raw::c_void) -> FnPtr {
if ptr.is_null() {
FnPtr {
... | Rust | 0 |
/*
* Copyright (c) 2021 Works Applications Co., Ltd.
*
* 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 ... | Rust | 0 |
ora.contract.account_id(),
"ft_transfer",
transfer_args.to_string().as_bytes(),
near_sdk_sim::DEFAULT_GAS,
1,
)
.assert_success();
// call exit to near
let input = super::build_input(
"withdrawEthToNear(... | Rust | 0 |
fetchone()
return render_template('editar_calificacion.html', calificacion=calificacion)
@app.route('/calificaciones_estudiante/<int:estudiante_id>')
def calificaciones_estudiante(estudiante_id):
cursor.execute("""
SELECT C.nombre, Ca.calificacion, Ca.fecha
FROM Calif... | Python | 1 |
ceptualLoss(nn.Module):
r"""
Perceptual loss, VGG-based
https://arxiv.org/abs/1603.08155
https://github.com/dxyang/StyleTransfer/blob/master/utils.py
"""
def __init__(self, weights=[1.0, 1.0, 1.0, 1.0, 1.0]):
super(PerceptualLoss, self).__init__()
self.add_module('vgg', VGG16().... | Python | 1 |
, content_split)
}
} else {
(None, content)
}
}
#[cfg(not(feature = "preview_unstable"))]
fn split_document(content: &str) -> (Option<&str>, &str) {
static FRONT_MATTER_DIVIDE: once_cell::sync::Lazy<regex::Regex> =
once_cell::sync::Lazy::new(|| {
regex::RegexBuilder::new... | Rust | 0 |
.group(1)
g_statisticsToolboxLicensesInUse = g_regExpMatch.group(2)
i = g_matlabLicenseOutputListLength
i = i + 1
g_string = 'Compiler licenses issued: [' + g_compilerLicensesIssued + \
'] : Compiler licenses in use: [' + g_compilerLicensesInUse + "]\n"
g_file_hand... | Python | 1 |
&& extent < min_extent {
min_extent = extent;
}
}
let tolerance = min_extent / Scalar::from_f64(1000.);
Tolerance::from_scalar(tolerance)?
}
Some(user_defined_tolerance) => user_defined_tolerance,
... | Rust | 0 |
self.assertTrue(np.allclose(out, correct))
def test_3x3_multi_channel(self):
# padding 'valid'
x = np.arange(40, dtype=np.float32).reshape((5, 4, 2))
out = self.layer3x3m.activate(x)
correct = np.array([[[-18], [-10]], [[14], [22]], [[46], [54]]])
self.assertEqual(ou... | Python | 1 |
Adam(params, lr=args.lr)
criterion = nn.CrossEntropyLoss()
if args.cuda:
criterion.cuda()
if args.evaluate:
if model_ori is None:
test(model_test,evaluate=True)
else:
test(model_ori, evaluate=True)
exit()
for epoch in range(1, args.epochs + 1)... | Python | 1 |
是否使用模型的conv+bn融合技术 加速推理
if fuse:
model = model.fuse() # 将模型的conv+bn融合 可以加速推理
# 2.2、载入一些模型参数
# stride: 模型最大的下采样率 [8, 16, 32] 所有stride一般为32
stride = int(model.stride.max()) # model stride
# 确保输入图片的尺寸imgsz能整除stride=32 如果不能则调整为能被整除并返回
imgsz = check_img_size(imgsz, s=stride) # check im... | Python | 1 |
"W14")),
Subsignal("cs_n", Pins("W13")),
Subsignal("mosi", Pins("W16"), Misc("PULLDOWN=True")),
Subsignal("miso", Pins("W15"), Misc("PULLDOWN=True")),
# RX-Interface (LMS -> FPGA).
Subsignal("diq1", Pins("J17 H17 H19 K17 G17 V16 J19 M19 P17 N19 U17 U16")),
Subsignal("t... | Python | 1 |
result_two = thread_two.join();
let result_three = thread_three.join();
println!("time elapsed {:?}", now.elapsed());
println!(
"result {}",
result_one.unwrap() + result_two.unwrap() + result_three.unwrap()
);
}
use std::str::FromStr;
use std::fmt::{self, Display, Formatter};
use crate:... | Rust | 0 |
main() {
let args = env::args().collect::<Vec<_>>();
let file = fs::read_to_string(args[1].clone()).unwrap();
let chiton = Chiton::new(file.clone(), 1);
println!("Part 1: {:?}", chiton.dijkstra());
let chiton = Chiton::new(file, 5);
println!("Part 2: {:?}", chiton.dijkstra());
}
pub struct Pe... | Rust | 0 |
else: # not using parallel or evaluating
return self.module(inputs)
class my_DataParallelCriterion(DataParallel):
"""
Calculate loss in multiple-GPUs, which balance the memory usage for
Semantic Segmentation.
The targets are splitted across the specified devices by chunking in
... | Python | 1 |
default_app_config = 'allianceauth.eveonline.autogroups.apps.EveAutogroupsConfig'
| Python | 1 |
= [0u8; 32];
bytes[0] = 255;
// actual result here is mod PRIME
assert_eq!(
fp_256::Fp256::from(bytes).to_str_decimal().as_str(),
"50339226693086325302401222106137814970392790680417402014301307793518034905497"
);
}
#[test]
fn to_bytes() {
let... | Rust | 0 |
ag}",
"sort-version": tag,
"company": "PythonCore",
"tag": tag,
"run-for": [
{"tag": tag, "target": "python.exe"},
{"tag": tag, "target": "pythonw.exe", "windowed": 1},
{"tag": f"{tag}-64", "targe... | Python | 1 |
# -*- coding: utf-8 -*-
import scrapy
import re
class RenrenSpider(scrapy.Spider):
name = 'renren'
allowed_domains = ['renren.com']
# 个人中心页网址
start_urls = ['http://www.renren.com/972990680/profile']
def start_requests(self):
# 登录之后用 chrome 的 debug 工具从请求中获取的 cookies
cookiesstr = "an... | Python | 1 |
)) -> Option<(PileProvenance<Tally>, VotesWithSameTransferValue<'a>)> {
self.by_provenance.remove(key)
}
}
/// A helper for extract_all_ballots_ignoring_transfer_value and extract_all_ballots_separated_by_transfer_value
struct MergeVotesHelper<'a,Tally> {
tally : Tally,
sum : Option<VotesWithSameTr... | Rust | 0 |
&G_VSOP87C_Z2_SATURN },
aavsop87::VSOP87Coefficient2 { p_coefficients: &G_VSOP87C_Z3_SATURN },
aavsop87::VSOP87Coefficient2 { p_coefficients: &G_VSOP87C_Z4_SATURN },
aavsop87::VSOP87Coefficient2 { p_coefficients: &G_VSOP87C_Z5_SATURN }
];
pub fn x(jd: f64) -> f64
{
aavsop87::ca... | Rust | 0 |
ective {
ident: String::from("map"),
args: vec![String::from("\"_id\"")]
})
))
);
}
#[test]
fn valid_value_arg() {
let directive = r#"someString"#;
let parsed = parse_fragment_argument(directive);
assert_eq... | Rust | 0 |
import torch.nn as nn
import torch
class VGG(nn.Module):
def __init__(self, features, class_num=1000, init_weights=False, weights_path=None):
super(VGG, self).__init__()
self.features = features
self.classifier = nn.Sequential(
nn.Linear(512*7*7, 4096),
nn.ReLU(True... | Python | 1 |
"::",
stringify!(down)
)
);
}
pub type Menu_Hook = ::std::option::Option<unsafe extern "C" fn(arg1: *mut tagMENU)>;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct tagMENU {
pub height: ::std::os::raw::c_short,
pub width: ::std::os::raw::c_short,
pub rows: ::std::os::... | Rust | 0 |
&e])?;
// let revwalk = RevwalkBuilder::new(repo)
// .roots(smallvec![commit_b])
// .excluding(smallvec![commit_e])
// .build();
// dbg!(&commits);
// let oids = revwalk.map(|commit| Ok(commit.oid())).collect::<Vec<_>>()?;
// let expected = [commit_b.o... | Rust | 0 |
quote!{Self: #net_behv_event_proc<<#ty as #trait_to_impl>::OutEvent>},
quote!{<<#ty as #trait_to_impl>::ProtocolsHandler as #into_protocols_handler>::Handler: #protocols_handler<Substream = #substream_generic>},
// Note: this bound is required because of https://git... | Rust | 0 |
import click
from taskweaver.cli.util import require_workspace
@click.command()
@require_workspace()
@click.option(
"--host",
"-h",
default="localhost",
help="Host to run TaskWeaver web server",
type=str,
show_default=True,
)
@click.option("--port", "-p", default=8080, help="Port to run TaskW... | Python | 1 |
5, RedGreenBlue);
set_operating_mode_test!(set_mode_red_green, 6, RedGreen);
set_operating_mode_test!(set_mode_green_blue, 7, GreenBlue);
set_test!(
set_resolution_12,
set_resolution,
CONFIG1,
BF::RESOLUTION,
Resolution::Bit12
);
set_test!(
set_resolution_16,
set_resolution,
CONFIG1,
... | Rust | 0 |
r::Error>>;
fn call(&self, req: Request) -> Self::Future {
let (m, uri, _, _, body) = req.deconstruct();
let path = String::from(uri.path());
match m {
Get => {
info!("getting at {}, len {}",path, self.storage.borrow().len() );
match self.storage... | Rust | 0 |
#-*- coding: utf-8 -*-
'''
Author: Geekwolf
Blog: http://www.simlinux.com
'''
from django import forms
from content.models import Content, Type, Images, ZbxContent
from django.contrib.auth.models import Group
class TypeForm(forms.ModelForm):
class Meta:
model = Type
fields = ('name',)
... | Python | 1 |
:
padding = (term_width - len(line.strip())) // 2
print(" " * padding + line.strip())
def menu():
while True:
print_banner()
print(f"{Fore.GREEN}[1]{Style.RESET_ALL} Perform DNS enumeration")
print(f"{Fore.RED}[2]{Style.RESET_ALL} Exit")
choice = input(f"\n{Fore.BL... | Python | 1 |
class Solution:
def minimumSwaps(self, nums: List[int]) -> int:
minIndex = self._getLeftmostMinIndex(nums)
maxIndex = self._getRightmostMaxIndex(nums)
swaps = minIndex + (len(nums) - 1 - maxIndex)
return swaps if minIndex <= maxIndex else swaps - 1
def _getLeftmostMinIndex(self, nums: List[int]) ->... | Python | 1 |
ref.strip().split()
n_err += editdistance.eval(hypo, ref)
n_total += len(ref)
wer = 100 * n_err / n_total
wer_fn = f"{cfg.common_eval.results_path}/wer.{fid}"
with open(wer_fn, "w") as fo:
fo.write(f"WER: {wer}\n")
fo.write(f"err / num_ref_words = {n_err} / {n_total}\n\n")
... | Python | 1 |
pet
.find(|c: char| !c.is_whitespace())
.unwrap_or_else(|| test_snippet.len());
// From the end of the first line of comments to the next non-whitespace char.
let test_snippet = &test_snippet[..first];
// There were multiple line breaks which got trimmed to nothing.
count_newlines(test_... | Rust | 0 |
SCHEME = {"primary": "122;73;155",
"primaryContainer": "245;217;255",
"onPrimary": "255;255;255",
"onPrimaryContainer": "46;0;77",
"inversePrimary": "228;180;255",
"secondary": "103;89;110",
"secondaryContainer": "239;221;245",
"onSecondary": "255;25... | Python | 1 |
t = node.get_attr_datum_type("T")?;
let use_peephole = node.get_attr_opt_bool("use_peephole")?.unwrap_or(false);
if use_peephole {
unimplemented!("Block LSTM peeplholes");
}
Ok(expand(BlockLSTM::new(forget_bias, cell_clip, t, use_peephole)))
}
#[derive(Clone, Debug, new, Educe)]
#[educe(Hash)]... | Rust | 0 |
dup, y_dup, sample_weight=sw_dup)
)
assert_allclose(reg_2sw.coef_, reg_dup.coef_)
assert_allclose(reg_2sw.intercept_, reg_dup.intercept_)
def test_read_only_buffer():
"""Test that sparse coordinate descent works for read-only buffers"""
rng = np.random.RandomState(0)
clf = ElasticNet(alpha=0... | Python | 1 |
RetryMode::Exponential
}
}
/// The set of options that can be specified to influence how retry attempts are made,
/// and a failure is eligible to be retried.
#[derive(Clone, Debug)]
pub struct RetryOptions {
/// The algorithm to use for calculating retry delays.
mode: RetryMode,
/// The delay between... | Rust | 0 |
t rest_uri = jormungandr.rest_uri();
let block_id = jcli.rest().v0().tip(&rest_uri);
jcli.rest().v0().block().get(block_id, rest_uri);
}
#[test]
pub fn test_correct_error_is_returned_for_incorrect_block_id() {
let jcli: JCli = Default::default();
let incorrect_block_id = "e1049ea45726f0b1fc473af54f7065... | Rust | 0 |
"""
Some general class
"""
from ast import literal_eval
from typing import Callable
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.language_models.chat_models import (
BaseChatModel,
)
def default_promp(query: str) -> str:
"""
get... | Python | 1 |
None):
self.horizon = horizon
model_inputs, inputs = self.model_inputs(input_shape, conditions_shape)
out = Flatten()(inputs)
for units in self.layers:
out = self._residual_block(units, out)
if self.recursive_forecast:
out = Dense(units=1, activation='line... | Python | 1 |
for EnumMap<K, V> {
fn eq(&self, other: &Self) -> bool {
self.as_slice() == other.as_slice()
}
}
impl<K: Internal<V>, V: Eq> Eq for EnumMap<K, V> {}
impl<K: Internal<V>, V: Hash> Hash for EnumMap<K, V> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_slice().hash(state);
}
}
impl... | Rust | 0 |
pkt this struct will be filled with the contents of the filtered"]
#[doc = " packet. It is owned by the caller and must be freed using"]
#[doc = " av_packet_unref() when it is no longer needed."]
#[doc = " This parameter should be \"clean\" (i.e. freshly allo... | Rust | 0 |
'account_id': 'account_2401',
'amount_type': 'percentage',
'tax_ids': [
Command.set([
'tax_ust_7_taxinclusive_skr03',
]),
],
... | Python | 1 |
ith_fallback() -> String {
match Self::resolve_ap() {
Ok(ap) => ap,
Err(err) => {
log::error!("using AP fallback, error while resolving: {:?}", err);
AP_FALLBACK.into()
}
}
}
pub fn resolve_ap() -> Result<String, Error> {
... | Rust | 0 |
string() + ".pos",
tract_core::ops::math::add::unary(minus_bias),
&inputs,
)?;
let test_neg = model.wire_node(
name.to_string() + ".test_neg",
tract_core::ops::logic::greater::unary(minus_lambda),
&inputs,
)?;
let neg = model.wire_node(
name.to_string() + ... | Rust | 0 |
#!/usr/bin/env python
import sys
from os.path import exists as path_exists
from pyscaffold.api import create_project
from pyscaffold.cli import run
from pyscaffold.extensions.cirrus import Cirrus
def test_create_project_with_cirrus(tmpfolder):
# Given options with the cirrus extension,
opts = dict(project_pa... | Python | 1 |
field2: 20,
field3: 30,
field15: _name,
field12: false,
field13: 70,
field14: 80,
field16: 90,
field19: 100,
field20: true,
field28: false,
field21: 110,
field22: 120,
field23: false,
field206: true,
... | Rust | 0 |
ns.
"""
prefix_padding_ms: int
"""Used only for `server_vad` mode.
Amount of audio to include before the VAD detected speech (in milliseconds).
Defaults to 300ms.
"""
silence_duration_ms: int
"""Used only for `server_vad` mode.
Duration of silence to detect speech stop (in millis... | Python | 1 |
);
}
matrix(y, self.row, self.col, self.shape)
}
_ => self.fmap(|x| x * other),
}
}
}
impl Mul<i64> for Matrix {
type Output = Self;
fn mul(self, other: i64) -> Self {
self.mul(other as f64)
}
}
impl Mul<i32> for Matrix {
typ... | Rust | 0 |
# ╔═════════════════════════════════════╗
# ║ Autor: Kenys Alvarado ║
# ║ GitHub: https://github.com/Kenysdev ║
# ║ 2024 - Python ║
# ╚═════════════════════════════════════╝
# -----------------------------------
# * ASINCRONÍA
# -----------------------------------
"""
* EJERCICIO #... | Python | 1 |
x1EF6, "M", "ỷ"),
(0x1EF7, "V"),
(0x1EF8, "M", "ỹ"),
(0x1EF9, "V"),
(0x1EFA, "M", "ỻ"),
(0x1EFB, "V"),
(0x1EFC, "M", "ỽ"),
(0x1EFD, "V"),
(0x1EFE, "M", "ỿ"),
(0x1EFF, "V"),
(0x1F08, "M", "ἀ"),
(0x1F09, "M", "ἁ"),
(0x1F0A, "M... | Python | 1 |
:3}: {train_loss:8.4f} {train_mae:8.4f}\
{train_elapsed:8.2f}s")
if train_loss < best_train:
best_train = train_loss
torch.save(self.nn.state_dict(), model_save_path,
_use_new_zipfile_serialization=False)
del train_loader
del valid_loader
... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models,fields, api, _
class CrmTeam(models.Model):
_inherit = 'crm.team'
def _compute_dashboard_button_name(self):
super(CrmTeam, self)._compute_dashboard_button_name()
teams_w... | Python | 1 |
ampler import TCRsampler
if default_background is None:
default_background = 'ruggiero_mouse_beta_t.tsv.sampler.tsv'
if default_background_if_missing is None:
default_background_if_missing = 'ruggiero_mouse_sampler.zip'
print(default_background)
try:
t = TCRsampler(default_background=default_background)
... | Python | 1 |
&mut but_break_pass.lock().unwrap(), &mut wind_pass.lock().unwrap(), handle) );
});
app.run().unwrap();
}
use actor_static::*;
struct Payload(usize);
impl Message for Payload {
type Result = usize;
}
struct Node {
id: usize,
next: Addr<Payload>,
chan: tokio::sync::mpsc::Sender<()>,
}
im... | Rust | 0 |
xample" testcase
# with a max score of zero is still properly rendered as
# correct or incorrect.
"score_fraction": st_score_fraction,
# But we also want the properly rounded score for display.
"score": rounded_score,
"max_s... | Python | 1 |
on_link = IDVerificationService.get_verify_location(course_id=course_key)
verification_data = {
'link': verification_link,
'status': verification_status['status'],
'status_date': verification_status['status_date'],
}
access_expiration = get_access_expiration_... | Python | 1 |
// Await until the command completes
let status = child.wait().await.context("ffmpeg")?;
match status.success() {
true => {
tokio::fs::remove_file(filename).await?;
Ok(Some(output_filename))
},
false => Ok(None),
}
}
async fn dl_file(url: &str) -> anyho... | Rust | 0 |
= 180 + 145 = 325
# Dan wins remaining 15
ending_values_bug_2 = [
('Ben', 2083), ('Eli', 2735), ('Gad', 2180)
]
# TEST BUG 2 **********************************************************
table = ['3d', '7c', '8h', 'Kd', 'Js']
player_dict_bug_3 = {
'Ben': {'cards': ['2s', ... | Python | 1 |
arameters.
///
/// # Example
///
/// ```
/// let pkcs7 = neo_mime::MediaRange::parse(
/// "application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m"
/// ).unwrap();
///
/// let mut params = pkcs7.params();
///
/// let (name, value) = params.next().unwrap();
/... | Rust | 0 |
and()
@commands.has_any_role(*OWNER_ROLES)
async def applicationdeny(ctx, member: discord.Member, *, reason: str = "No specific reason provided."):
try:
await member.send(f"❌ Your staff application has been denied.\n**Reason:** {reason}\nYou are welcome to reapply in the future.")
except discord.Forbidd... | Python | 1 |
at prompts the user to enter a base number and an
# exponent, and then calculates the power of the base to the exponent. The program
# should not use the exponentiation operator (**) or the math.pow() function. The
# program should handle both positive and negative exponents.
base = float(input("Enter the base number... | Python | 1 |
Error = crate::Error;
fn try_from(s: &'a str) -> Result<Self, Self::Error> {
$validate_id(s)?;
Ok($id::from_borrowed(s))
}
}
impl std::str::FromStr for Box<$id> {
type Err = crate::Error;
fn from_str(s: &str) -> Result<S... | Rust | 0 |
import bpy
import bmesh
from .helpers import edit_mesh_elements
from ..math import get_dist_sq
class GRET_OT_shape_key_select(bpy.types.Operator):
"""Select vertices affected by the current shape key"""
bl_idname = 'gret.shape_key_select'
bl_label = "Select Shape Key"
bl_context = 'objectmode'
bl... | Python | 1 |
son2", 0x100180 ),
( "file_type_json5", 0x100181 ),
( "file_type_jsonld", 0x100182 ),
( "file_type_jsonnet", 0x100183 ),
( "file_type_json_official", 0x100184 ),
( "file_type_json", 0x100185 ),
( "file_type_jsp", 0x100186 ),
( "file_type_jss", 0x100187 ),
( "file_type_js", 0x100188 ),
( "file_type_julia2", 0x100189 ),
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.