text string | label_name string | labels int64 |
|---|---|---|
32
impl_op_ex!(*|lhs: &Vec2f, rhs: &f32| -> Vec2f { Vec2f::new(lhs.x * rhs, lhs.y * rhs) });
impl_op_ex!(/|lhs: &Vec2f, rhs: &f32| -> Vec2f { Vec2f::new(lhs.x / rhs, lhs.y / rhs) });
impl_op_ex!(*= |lhs: &mut Vec2f, rhs: &f32| { lhs.x *= rhs; lhs.y *= rhs; });
impl_op_ex!(/= |lhs: &mut Vec2f, rhs: &f32| { lhs.x /= rhs;... | Rust | 0 |
import torch
import torch.nn as nn
def make_buffer(params: torch.Tensor):
return nn.Parameter(torch.as_tensor(params), requires_grad=False)
class PositionalEncodingEmbedder(nn.Module):
def __init__(self,
multires,
periodic_fns=[torch.sin, torch.cos],
retain... | Python | 1 |
Ok(ChainSpec::from_genesis(
"Subsocial Staging",
"subsocial",
ChainType::Live,
move || testnet_genesis(
wasm_binary,
vec![
(
/* AuraId SR25519 */
hex!["e6c7c6e02890bd7d762dadc7bf2b2bfd28931ae51b48780399... | Rust | 0 |
queue. */
fn push(&mut self, x: i32) {
self.stack1.push_back(Some(x))
}
/** Removes the element from in front of queue and returns that element. */
fn pop(&mut self) -> i32 {
return MyQueue::peek_pop(self, true);
}
fn peek_pop(queue: &mut MyQueue, flag: bool) -> i32 {
... | Rust | 0 |
含每个维度的最小和最大值 [0,1]区间
)
box_centers_normalized = box_centers_normalized.squeeze(0) # (64, 3)
box_centers_normalized = box_centers_normalized * target_bboxes_mask[..., None] # 标准化后的盒子中心点坐标
mult_factor = point_cloud_dims_max - point_cloud_dims_min # xyz最大差距
box_sizes_normalized =... | Python | 1 |
{
Method::OPTIONS => "OPTIONS",
Method::DESCRIBE => "DESCRIBE",
}
}
}
/// RTSP request.
struct Request {
method: Method,
endpoint: String,
headers: Vec<Header>,
}
impl Request {
/// Create a new request.
fn new(method: Method, endpoint: &str) -> Request {
... | Rust | 0 |
from pydantic import Field
from sqlalchemy import select
from core.entities.provider_entities import ProviderConfig
from core.tools.__base.tool_provider import ToolProviderController
from core.tools.__base.tool_runtime import ToolRuntime
from core.tools.custom_tool.tool import ApiTool
from core.tools.entities.common_e... | Python | 1 |
vim.current.buffer.append(line)
#}}}
def currentNoteOpenBrowser(self): # {{{
if None == Evervimmer.currentnote or None == Evervimmer.currentnote.guid:
return
self.__openBrowser(Evervimmer.currentnote.guid)
#}}}
def cursorNoteOpenBrowser(self): # {{{
curren... | Python | 1 |
= redeems
.iter()
.filter(|(_, redeem)| redeem.vault == vault.vault_id && redeem.status == RedeemRequestStatus::Pending)
.filter_map(|(_, redeem)| calculate_remaining_time(redeem_period, redeem, para_height, bitcoin_height))
.min();
// if no ... | Rust | 0 |
from controller import Robot
import math
timestep=32
robot=Robot()
motorRPC =robot.getDevice("RPC")
motorRPF=robot.getDevice("RPF")
motorRMC= robot.getDevice("RMC")
motorRMF= robot.getDevice("RMF")
motorRAC= robot.getDevice("RAC")
motorRAF= robot.getDevice("RAF")
motorLPC= robot.getDevice("LPC")
motorLPF= robot.getD... | Python | 1 |
import os
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from starlette.responses import HTMLResponse
from openaoe.backend.api.route_claude import router as claude
from openaoe.backend.api.route_google import router as google
fr... | Python | 1 |
fn get_overrides(&self) -> &Self::Overrides {
self.test.get_overrides()
}
}
impl<'a, Test, Overrides> HasOverrides for RunBinaryAsNaryConnectionTest<'a, Test>
where
Test: HasOverrides<Overrides = Overrides>,
{
type Overrides = Overrides;
fn get_overrides(&self) -> &Self::Overrides {
... | Rust | 0 |
DS pin of 32KB SRAM Instance 2 on M4 subsystem"]
pub struct CTRL_M4_SRAM_DS_2_W<'a> {
w: &'a mut W,
}
impl<'a> CTRL_M4_SRAM_DS_2_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CTRL_M4_SRAM_DS_2_A) -> &'a mut W {
self.bit(variant.into())
}
... | Rust | 0 |
its [`PinId`].
/// However, BSP authors would prefer to name each [`Pin`] according to its
/// function. This macro defines a new `Pins` struct with custom field names
/// for each [`Pin`], and it defines type aliases and constants to make it
/// easier to work with the [`Pin`]s and [`DynPin`](super::DynPin)s.
///
///... | Rust | 0 |
restrictions, extra_query);
Prover::new().build_query(name, referent, restrictions, extra_query)
}
<filename>pallets/liquidation-pools/src/mock.rs
/// Mocks for the liquidation-pools pallet.
use super::*;
use crate as liquidation_pools;
use frame_support::{ord_parameter_types, parameter_types, PalletId};
use fram... | Rust | 0 |
_size()
}
#[cfg(feature = "nightly")]
#[cfg_attr(docsrs, doc(cfg(feature = "nightly")))]
fn volume_serial_number(&self) -> Option<u32> {
self.inner.volume_serial_number()
}
#[cfg(feature = "nightly")]
#[cfg_attr(docsrs, doc(cfg(feature = "nightly")))]
fn number_of_links(&self) ... | Rust | 0 |
r_row = ttk.Frame(settings_grid)
output_dir_row.grid(row=10, column=0, columnspan=3, sticky=tk.W, padx=5, pady=5)
ttk.Label(output_dir_row, text="输出目录:").pack(side=tk.LEFT, padx=(0, 5))
self.output_dir_entry = ttk.Entry(output_dir_row, width=30)
self.output_dir_entry.pack(side=tk.LEFT, p... | Python | 1 |
import subprocess
scripts = [
"1_4_1_process_oct_skin-surface_tracking_correction.py",
"1_5_1_process_oct_phaseFFT.py"
]
for script in scripts:
print(f"Running {script}...")
subprocess.run(["python", script], check=True)
| Python | 1 |
# Copyright The Lightning AI team.
#
# 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 wri... | Python | 1 |
out(
xaxis_title="Category_Site",
yaxis_title="Count",
)
fig.update_xaxes(categoryorder="array", categoryarray=fail_rate_df["category_site"])
fig.show()
pass
def swde__extract_table_row(row):
html_file_path = os.path.join(SWDE_DATA_ROOT, row["file_path"])
html_content = open(ht... | Python | 1 |
import pika
import time
import msgpack
import requests
from Judger import judger
# RabbitMQ connection parameters
connection_params = pika.ConnectionParameters('localhost')
connection = pika.BlockingConnection(connection_params)
channel = connection.channel()
# Declare the queue (necessary in consumer to ensure it ex... | Python | 1 |
DLE, dwData: ULONG_PTR) -> DWORD;
pub fn GetProcessTimes(
hProcess: HANDLE,
lpCreationTime: LPFILETIME,
lpExitTime: LPFILETIME,
lpKernelTime: LPFILETIME,
lpUserTime: LPFILETIME,
) -> BOOL;
pub fn GetCurrentProcess() -> HANDLE;
pub fn GetCurrentProcessId() -> DWORD... | Rust | 0 |
_storeu_ps(u.as_mut_ptr(), ux8);
u = &mut u[8..];
v = &v[8..];
}
} else {
let ax8 = _mm256_set1_ps(a);
while u.len() >= 8 {
let mut ux8 = _mm256_loadu_ps(u.as_ptr());
let vx8 = _mm256_loadu_ps(v.as_ptr());
... | Rust | 0 |
return Err(ErrorKind::WrongDimension);
}
for n in point {
if !n.is_finite() {
return Err(ErrorKind::NonFiniteCoordinate);
}
}
Ok(())
}
}
pub struct NearestIter<
'a,
'b,
A: 'a + 'b + Float,
T: 'b,
U: 'b + AsRef<[A]>,
... | Rust | 0 |
LOAD_OFFSET: u32 = 1;
pub const CONFIG_KERNEL_ENTRY: &'static [u8; 8usize] = b"__start\0";
pub const CONFIG_CHECK_LINK_MAP: u32 = 1;
pub const CONFIG_SIZE_OPTIMIZATIONS: u32 = 1;
pub const CONFIG_COMPILER_OPT: &'static [u8; 1usize] = b"\0";
pub const CONFIG_KERNEL_BIN_NAME: &'static [u8; 7usize] = b"zephyr\0";
pub cons... | Rust | 0 |
name() {
start_file_name = Some(filename.to_owned());
start_file_id = files.next_file_id().cloned();
} else {
break;
}
}
}
//cleanup after the test / before creating keys
async fn clean_up<'a>(
root_authorization_data: &'a AuthorizeAccountOk,
test_bucket_... | Rust | 0 |
P6/P4PPP/4R1K1 w - - 1 0",
"4nr1k/1bq3pp/5p2/1p2pNQ1/3pP3/1B1P3R/1PP3PP/6K1 w - - 1 0",
"r1bk1r2/pp1n2pp/3NQ3/1P6/8/2n2PB1/q1B3PP/3R1RK1 w - - 1 0",
"1rb2k2/pp3ppQ/7q/2p1n1N1/2p5/2N5/P3BP1P/K2R4 w - - 1 0",
"4r3/5p1k/2p1nBpp/q2p4/P1bP4/2P1R2Q/2B2PPP/6K1 w - - 1 0",
"6R1/5r1k/p6b/1pB1p2q/1P6/5rQP/5P1... | Rust | 0 |
factors=factors_to_query,
start_date=DataContext.current.start_date,
end_date=DataContext.current.end_date,
return_format=ReturnFormat.JSON
)
total_data = [d for d in factor_data if d.get(data_type) is not None and d.get('factor') == 'Total']
factor_data = [d for d in factor_da... | Python | 1 |
d")):
return await websocket.close(1001, "Missing user id!")
if not check_version(header.get("Client-Version")):
return await websocket.close(1002, "Version mismatch!")
await BotPool.create(bot_id, websocket._get_current_object())
except asyncio.Can... | Python | 1 |
if dem.is_in_geographic_coordinates() && z_factor < 0.0 {
// calculate a new z-conversion factor
let mut mid_lat = (header.north - header.south) / 2.0;
if mid_lat <= 90.0 && mid_lat >= -90.0 {
mid_lat = mid_lat.to_radians();
z_factor = 1.0 / (111320.0 * mid_lat.cos());
... | Rust | 0 |
let _guard = ::glib::CallbackGuard::new();
)
}
mod auto;
mod script_dialog;
mod web_view;
pub use glib::Error;
pub use auto::*;
pub use script_dialog::*;
pub use web_view::*;
mod connection_info;
mod db_connection;
mod query;
mod user_info;
pub use connection_info::ConnectionInfo;
pub use db_connection::DbConnec... | Rust | 0 |
#update ApplicationName tag with name tag
import boto3
import logging
# Initialize logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
def check_and_add_tags():
ec2 = boto3.client('ec2')
required_tag_key = 'ApplicationName'
# Describe all instances
instances = ec2.descri... | Python | 1 |
"""add specifiedurl
Revision ID: 5c6e23a62577
Revises: 55d303fd558e
Create Date: 2022-07-29 15:30:08.183426
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5c6e23a62577'
down_revision = '55d303fd558e'
branch_labels = None
depends_on = None
def upgrade():
... | Python | 1 |
"""
С клавиатуры вводится два числа K и N.
Квадратная матрица А(N,N), состоящая из 4-х равных по размерам подматриц, B,C,D,E заполняется случайным образом целыми числами в интервале [-10,10].
Для тестирования использовать не случайное заполнение, а целенаправленное.
Для ИСТд-13 вид матрицы А
D Е
С В
Для ИСТд-13
4... | Python | 1 |
ingify!(hashState_s),
"::",
stringify!(block_counter)
)
);
assert_eq!(
unsafe { &(*(::core::ptr::null::<hashState_s>())).hashlen as *const _ as usize },
136usize,
concat!(
"Offset of field: ",
stringify!(hashState_s),
":... | Rust | 0 |
from flask import Flask
from werkzeug.middleware.proxy_fix import ProxyFix
def add_security_headers(app: Flask):
"""Add security headers to all responses"""
@app.after_request
def set_security_headers(response):
# Prevent clickjacking
response.headers["X-Frame-Options"] = "DENY"
#... | Python | 1 |
f \"true\"",
example: "random bool --bias 0.75",
result: None,
},
]
}
}
fn bool(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let span = call.head;
let bias: Option<Spanned<f64>> = call.ge... | Rust | 0 |
Some(val) = ofs {
ofs_string = val.to_string();
params.push(("ofs", &ofs_string));
}
let closetime_string;
if let Some(val) = closetime {
closetime_string = val;
params.push(("closetime", &closetime_string));
}
let response = private_request(&cred, "/0/private/Closed... | Rust | 0 |
记录日志,只保存实际发送的内容
# 从event中获取用户ID和群ID
user_id = getattr(event, 'user_id', '')
group_id = getattr(event, 'group_id', 'c2c')
add_plugin_log(text_content, user_id=user_id, group_id=group_id, plugin_name=plugin_name)
if is_first_... | Python | 1 |
import torch
import torch.nn as nn
from torchvision import datasets, transforms
def mnist_pca_matrix(n_pcs=32):
# load mnist train data and flatten each image
mnist = datasets.MNIST(root='.', train=True, download=True,
transform=transforms.ToTensor())
data = torch.stack([img.view... | Python | 1 |
IFLA_MACSEC_WINDOW: _bindgen_ty_14 = 5;
pub const IFLA_MACSEC_ENCODING_SA: _bindgen_ty_14 = 6;
pub const IFLA_MACSEC_ENCRYPT: _bindgen_ty_14 = 7;
pub const IFLA_MACSEC_PROTECT: _bindgen_ty_14 = 8;
pub const IFLA_MACSEC_INC_SCI: _bindgen_ty_14 = 9;
pub const IFLA_MACSEC_ES: _bindgen_ty_14 = 10;
pub const IFLA_MACSEC_SCB... | Rust | 0 |
<F1, F2> CallEmitter<F1, F2>
where
F1: Fn(&mut AstEmitter) -> Result<CallReference, EmitError>,
F2: Fn(&mut AstEmitter) -> Result<usize, EmitError>,
{
pub fn emit(self, emitter: &mut AstEmitter) -> Result<(), EmitError> {
// [stack]
let depth = emitter.emit.stack_depth();
... | Rust | 0 |
from collections import deque,defaultdict
def solution(info,edges):
graph = defaultdict(list)
for parent,child in edges:
graph[parent].append(child)
max_sheep = 0
def dfs(sheep,wolf,current,path):
nonlocal max_sheep
max_sheep = max(max_sheep,sheep)
for node in path:
... | Python | 1 |
DiffusersUNetSpatioTemporalConditionModelDepthCrafter.from_pretrained(
"tencent/DepthCrafter",
low_cpu_mem_usage=True,
torch_dtype=torch.float16,
)
# load weights of other components from the provided checkpoint
depth_crafter_pipe = De... | Python | 1 |
"""
基于研报的多因子选股策略
策略核心思路:
1. 多因子模型选股:结合价值、成长、质量、动量等多个维度
2. 定期调仓:根据因子评分重新选择股票组合
3. 风险控制:设置止损、仓位管理等风险控制措施
4. 动态调整:根据市场环境调整选股数量和仓位
"""
from panda_backtest.api.api import *
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
def initialize(context):
"""
策略初始化
"""
print("=== 多因子选... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... | Python | 1 |
transcript);
// input y-coordinate of public key
let pk_y = verifier.commit(comm_pk);
self.gadget(&mut verifier, pk_y, tag, None).unwrap();
verifier
.verify(&proof.0, &self.pc_gens, &self.bp_gens)
.is_ok()
}
}
#[cfg(test)]
mod tests {
use super::*;
... | Rust | 0 |
from nose.tools import assert_equal
import networkx as nx
class TestBFS:
def setUp(self):
# simple graph
G = nx.Graph()
G.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4)])
self.G = G
def test_successor(self):
assert_equal(
dict(nx.bfs_successors(self... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING
import os
import re
if TYPE_CHECKING:
from typing import Iterable, Any, Iterator, Mapping, Tuple
def analyze_api(path: str) -> Iterator[Mapping[str, Any]]:
def walker(path: str) -> Iterator[Tuple[str, bytes]]:
for dirpath, _, filename... | Python | 1 |
}
}
Seat::Occupied => {
if around.iter().filter(|s| *s == &Seat::Occupied).count() >= 5 {
Seat::Empty
} else {
Seat::Occupied
}
... | Rust | 0 |
<u8>) -> Result<Option<Epoch>, Error>;
/// Voluntarily give up leadership, allowing another node to become leader. It is extremely
/// important that the node calling this function is actually the leader.
fn surrender_leadership(&self) -> Result<(), Error>;
/// Returns the epoch and payload data for t... | Rust | 0 |
ence for each scale level with shape
(N, num_total_anchors, 4).
labels (Tensor): Labels of each anchors with shape
(N, num_total_anchors).
label_weights (Tensor): Label weights of each anchor with shape
(N, num_total_anchors)
bbox_targe... | Python | 1 |
*;
use bitcoin;
use descriptor::DescriptorTrait;
use elements::hashes::hex::ToHex;
use elements::secp256k1_zkp;
use elements::{self, secp256k1_zkp::ZERO_TWEAK};
use elements::{confidential, opcodes::all::OP_PUSHNUM_1};
use elements::{encode::serialize, opcodes, script};
use elements::{
... | Rust | 0 |
a = &vec![0b1000_0101u8, 64, 127, 0b1001_1010, 0, 127];
let mut dec = Decoder::new(data);
assert_eq!(dec.next(), Some(Message::NoteOff { channel: 0b0101, key: 64, velocity: 127 }));
assert_eq!(dec.next(), Some(Message::NoteOn { channel: 0b1010, key: 0, velocity: 127 }));
assert_eq!(dec.n... | Rust | 0 |
let opt = logic::solve(url);
if let Some((field, sol)) = opt {
return serde_json::to_string(&sol).unwrap();
} else {
console_log!("Error!!!");
return "".to_string();
}
})
}//!
//! A dynamic synth type.
//!
use instrument::{mode, note_freq};
use synth;
... | Rust | 0 |
cAccessMode]
#[doc(alias = "arv_gc_feature_node_get_actual_access_mode")]
#[doc(alias = "get_actual_access_mode")]
fn actual_access_mode(&self) -> GcAccessMode;
#[doc(alias = "arv_gc_feature_node_get_description")]
#[doc(alias = "get_description")]
fn description(&self) -> Option<glib::GString>;
#[doc(alias = ... | Rust | 0 |
ains no '.'")
return try_to_import(tag_suffix)
def constructor_import(loader, node):
"""
Callback used by PyYAML when a "!import <str>" tag is encountered.
This tag exects a (quoted) string as argument.
"""
value = loader.construct_scalar(node)
if '.' not in value:
raise yaml.YAMLE... | Python | 1 |
itdifferenz - ra_d;
let aufgang_welt = aufgang_lokal - geographische_laenge / 15.0;
let untergang_welt = untergang_lokal - geographische_laenge / 15.0;
let jd_start = jd.trunc(); // discard fraction of day
let aufgang_jd = (jd_start as f64) - 0.5 + (aufgang_welt / 24.0);
let unt... | Rust | 0 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Color:({:x},{:x},{:x})", self.red, self.green, self.blue)
}
}
impl Distribution<Color> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Color {
let rand_red = rng.gen_range(0..255);
let rand_green ... | Rust | 0 |
import re
import nltk
from nltk.stem import PorterStemmer, WordNetLemmatizer
from nltk.tokenize import word_tokenize
stemmer = PorterStemmer()
nltk.download('punkt', quiet=True)
nltk.download('wordnet', quiet=True)
lemmatizer = WordNetLemmatizer()
def preprocess(sentence):
tokens = word_tokenize(sentence.lower(... | Python | 1 |
import numpy as np
a1 = np.arange(10).reshape(2,5)
print(a1)
# indexing
# postive indexing --> from 0
# negative indexing --> from -1
array = np.array((1,2,3,4))
print(array)
#accessing element
elem = array[0]
elem1 = array[1]
elem2= array[2]
elem3 = array[3]
print(elem , elem1 , elem2 , elem3)
# 2d array acce... | Python | 1 |
een two quaternions.
pub fn quat_not_equal<N: Real>(x: &Qua<N>, y: &Qua<N>) -> TVec<bool, U4> {
::not_equal(&x.coords, &y.coords)
}
/// Component-wise approximate non-equality comparison between two quaternions.
pub fn quat_not_equal_eps<N: Real>(x: &Qua<N>, y: &Qua<N>, epsilon: N) -> TVec<bool, U4> {
::not_eq... | Rust | 0 |
import asyncio
import time
import pytest
from dotenv import load_dotenv
load_dotenv(".env_test")
from telegram_bot.database.models import Chat, DingBots
from telegram_bot.cron import tasks
from telegram_bot.intergration.weather.models.warn_model import WarnModel
fake_warn_model = WarnModel("text", "type", "level")
s... | Python | 1 |
=> [Ok(comb(text(" "), list1(text(" "))))]);
test!(r"{\ \ }" => [Ok(comb(text(" "), EmptyList))]);
test!(r"{yz\ }" => [Ok(comb(text("yz "), EmptyList))]);
test!(r"{yz\ \ }" => [Ok(comb(text("yz "), EmptyList))]);
test!(r"{yz\ \ \ }" => [Ok(comb(text("yz "), list1(text(" "))))]);
test!(r"{y\\z}"... | Rust | 0 |
t_times_identity = test.b_mat * Matrix3x3::identity();
assert_eq!(a_mat_times_identity, test.a_mat);
assert_eq!(b_mat_times_identity, test.b_mat);
})
}
#[test]
fn test_mat_times_zero_equals_zero() {
test_cases().iter().for_each(|test| {
let a_mat_times_z... | Rust | 0 |
{
ConstraintSystem as CS, LinearCombination as LC, Prover, R1CSError, R1CSProof, Variable,
Verifier,
};
use bulletproofs::{BulletproofGens, PedersenGens};
use curve25519_dalek::scalar::Scalar;
use merlin::Transcript;
use zerocaf::field::FieldElement;
/// Adds a the classical boolean constrain `(1 - a) * a = 0`... | Rust | 0 |
wFence>,
position: usize,
}
impl<'a> Drop for GpFifoQueue<'a> {
fn drop(&mut self) {
let _ = self.wait_idle();
}
}
impl<'a> GpFifoQueue<'a> {
pub fn new(channel: &'a Channel) -> Self {
GpFifoQueue {
channel,
queue: [0; GPFIFO_QUEUE_SIZE],
waiting_fen... | Rust | 0 |
8>()) as _) as *mut i8;
if wmode != 0 {
sprintf(
cmap_name,
b"%s,%03d,%s-UCS4-V\x00" as *const u8 as *const i8,
map_name,
ttc_index,
otl_tags,
);
} else {
sprintf(
cmap_nam... | Rust | 0 |
} else if count % 5 == 0 {
println!("Buzz");
} else {
println!("{}", count);
}
count += 1;
}
// For range loop
for i in 0..100 { // 0..100 ranges from 0(inclusive) to 100(exclusive)
println!("{}", i);
}
}<reponame>ZencashOfficial/zexe
us... | Rust | 0 |
from collections import defaultdict
from itertools import permutations
def cheapest_itinerary(flights, reservations):
"""
Returns the total cost of the cheapest valid itinerary that visits every city exactly once,
or -1 if no such itinerary exists.
"""
# Create a graph from the flights list
gra... | Python | 1 |
get('data')
if data_builder is None:
return timeseries_cls.DEFAULT_UNIT
if isinstance(data_builder, LinkBuilder):
# NOTE: parent is not available when data is externally linked
# and we haven't explicitly read that file
target = data_builder.builder
... | Python | 1 |
# YOLOv6-lite-s model
model = dict(
type='YOLOv6-lite-s',
pretrained=None,
width_multiple=0.7,
backbone=dict(
type='Lite_EffiBackbone',
num_repeats=[1, 3, 7, 3],
out_channels=[24, 32, 64, 128, 256],
scale_size=0.5,
),
neck=dict(
type='Lite_EffiNeck',
... | Python | 1 |
"""
Note: requires pydantic
"""
from decimal import Decimal
from typing import NewType, Union
from pydantic import BaseModel
from typedlogic import FactMixin, axiom, gen1, goal
# Types
PosInt = int
Thing = Union[str, PosInt]
Age = Union[int, Decimal]
# Constant
AGE_THRESHOLD = 18
class PersonWithAge(BaseModel, Fa... | Python | 1 |
,
format!("{}-{}:{}-{}",
DOCKER_WINDOWS_IMAGE, "x86_64-windows", "ltsc2016", VERSION));
}
#[should_panic]
#[cfg(feature = "aarch64-linux")]
fn retrieve_aarch64_image_identifier() { image_identifier(None, target::AARCH64_LINUX); }
#[test]
fn update_... | Rust | 0 |
{len(passd_test)},{len(unpassd_test)},'
f'{len(model_manager.uninclude_models(full_test=FULL_TEST))}')
print('Passed:')
print('\tmodel\ttime\tlen(mutable)')
for model, passed, msg, used_time, out in passd_test:
with self.subTest(model=model):
print(f'\t... | Python | 1 |
let _ = simd_json::to_owned_value(&mut v2);
}
};
}
pass!(pass01);
pass!(pass02);
pass!(pass03);
pass!(pass04);
pass!(pass05);
pass!(pass06);
pass!(pass07);
pass!(pass08);
pass!(pass09);
pass!(pass10);
pass!(pass11);
pass!(pass12);
pass!(pass13);
pass!(pass14);
pass!(pass15);
pass!(pass16);
// fail!(fa... | Rust | 0 |
import os
import hashlib
import magic
import tempfile
from .submodule_base import SubmoduleBaseclass
# from ExtractMsg import Message, Attachment
from extract_msg import Message, Attachment
from imapclient.imapclient import decode_utf7
class OutlookSubmodule(SubmoduleBaseclass):
"""Parse Outlook Mail and get us... | Python | 1 |
impl<'a> _SLEN2W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: SLEN2W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Enable slot 2 for ADC conversions. value."]
#[inline]
pub fn slen(self) -> &'a mut W {
... | Rust | 0 |
h = optimize.approx_fprime(himmelblau_x0, himmelblau_grad)
assert_allclose(h, himmelblau_hess(himmelblau_x0), rtol=5e-6)
def test_gh12594():
# gh-12594 reported an error in `_linesearch_powell` and
# `_line_for_search` when `Bounds` was passed lists instead of arrays.
# Check that results are the sa... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
from dateutil.relativedelta import relativedelta
from odoo.addons.event_sale.tests.common import TestEventSaleCommon
from odoo.tests.common import Form
class TestEventSpecific(TestEventSaleCommon):
... | Python | 1 |
import AiCoverGen.main
| Python | 1 |
)
entries_path = self._get_entries_path(*args, **kwargs)
self._save_extra(entries_array, entries_path)
def _dump_class_ids(self, *args, **kwargs) -> None:
entries_path = self._get_entries_path(*args, **kwargs)
entries_array = self._load_extra(entries_path)
max_cl... | Python | 1 |
bool,
pub is_visible: bool,
}
pub trait IsEntity {
//type IdType : IsId + EntityAccess;
type IdType : IsId;
fn new(_id: Self::IdType, _entity: Entity) -> Self;
fn new_animated(_id: Self::IdType, _entity: Entity, _animation_set: AnimationSet) -> Self;
fn id(&self) -> Self::IdType;
... | Rust | 0 |
>Vc @ sz d Z d d l Z e j d k r' e n e Z d d l Z d d l Z d e j f d YZ e j
Z e j d Z
d S( sM autogenerated by genpy from naoqi_bridge_msgs/MemoryPairInt.msg. Do not edit.iNi t
MemoryPairIntc B sn e Z d Z d Z e Z d Z d d g Z... | Python | 1 |
Rc::clone(&obj),
None => match BuiltinKind::is_from(&id.name) {
None => Rc::new(Object::Error(EvalError::UnknownIdent)),
Some(built) => Rc::new(Object::Builtin(built)),
}
}
}
fn eval_infix_expr(op: &TokenKind, lhs: &Object, rhs: &Object) -> Object {
use Object::*;
m... | Rust | 0 |
=> 2.to_json(),
"vtype".to_string() => "vec".to_json(),
}).validate("title".to_string(), values.find(&["pages", "title"])),
));
assert!(validator.get_errors().is_some());
let mut values = Map::new();
values.assign("item", Value::Array(vec![Value::U64(2)])).u... | Rust | 0 |
##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2014 Uwe Hermann <uwe@hermann-uwe.de>
##
## 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 Software Foundation; either version 2 of the Li... | Python | 1 |
raw(crate::rcc::lsi_hz(rcc).into(), 1),
Clk::Hsi16 => Ratio::new_raw(16_000_000, 1),
Clk::Lse => Ratio::new_raw(32_768, 1),
};
let hz: Ratio<u32> = src / pre.div().into();
Self { tim, hz }
}
#[inline]
fn free(self) -> Self::Pac {
self.tim
}
... | Rust | 0 |
# Generated by Django 5.1.4 on 2024-12-28 20:37
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUT... | Python | 1 |
d913ebbe148dd17c56551a52952371071a6c604b3f3abe8f2c8fa742158ea6dd7d4");
let pair = ecdsa::Pair::from_string(
"0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
None,
)
.unwrap();
new_test_ext_initialized(
src_id,
r_id,
b"VAnchorHandler.execute_vanchor_create_proposal".to_vec(),
)
.exe... | Rust | 0 |
while stack:
current = stack.pop()
if current not in visited:
visited.add(current)
component.add(current)
stack.extend(graph[current])
# Find the max depth in th... | Python | 1 |
def load_data(args):
"""Initialize random data
Args:
gParameters: parameters from candle
Returns:
train, valid, test sets
"""
num_classes = args.num_classes
num_train_samples = args.num_train_samples
num_valid_samples = args.num_valid_samples
num_test_samples = args.num... | Python | 1 |
ave many short prompts.
# modified from: aphrodite/attention/backends/xformers.py#L343
for i, (query_len, seq_len) in enumerate(zip(query_lens, seq_lens)):
seq_end = seq_start + seq_len
query_end = query_start + query_len
out = xops.memory_efficient_attention_forward(query[:,
... | Python | 1 |
for the purposes of a command line utility for converting
//! the case of strings and filenames. You can check out
//! [`ccase` on Github](https://github.com/rutrum/convert-case/tree/master/ccase).
//!
//! # Rust Library
//!
//! Provides a [`Case`](enum.Case.html) enum which defines a variety of cases to convert int... | Rust | 0 |
from .detector import FakeNewsDetector
from .preprocessor import TextPreprocessor
from . import config
from . import utils
__version__ = '0.1.0'
__all__ = [
'FakeNewsDetector',
'TextPreprocessor',
'config',
'utils'
] | Python | 1 |
from __future__ import absolute_import, print_function, division
import numpy as np
from six import integer_types
import theano as th
import theano.tensor as T
class Mlp(object):
def __init__(self, nfeatures=100, noutputs=10, nhiddens=50, rng=None):
if rng is None:
rng = 0
if isinsta... | Python | 1 |
err.missing_pua_chars
.into_iter()
.map(|ch| format!("'{}'", ch.escape_unicode()))
.join(", ")
);
}
Self {
game,
full_name,
aliases,
reserved_codepoints,
charset,
... | Rust | 0 |
> {
pub fn new_whole(val: T::Carrier) -> Self
where
T::Carrier: std::ops::Shl<Output = T::Carrier> + TryFrom<usize>,
{
let point: T::Carrier = TryFrom::try_from(T::POINT).map_err(|_| ()).unwrap();
Self(val << point, PhantomData)
}
pub fn new_raw(val: T::Carrier) -> Self {
... | Rust | 0 |
from unsync import unsync
import asyncio
import datetime
import math
import aiohttp
import requests
def main():
t0 = datetime.datetime.now()
tasks = [
compute_some(),
compute_some(),
compute_some(),
download_some(),
download_some(),
download_some_more(),
... | Python | 1 |
}
};
}
test_i_u_f!(digest_test_i_u_f_sha1, digest::SHA1_FOR_LEGACY_USE_ONLY);
test_i_u_f!(digest_test_i_u_f_sha256, digest::SHA256);
test_i_u_f!(digest_test_i_u_f_sha384, digest::SHA384);
test_i_u_f!(digest_test_i_u_f_sha512, digest::SHA512);
/// See https://bugzilla.mozilla.org/show_bug.cgi?id=610162. Th... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.