text string | label_name string | labels int64 |
|---|---|---|
if raw_result < 0 {
None
} else {
MidiNote::from_raw(raw_result as u8)
}
}
pub fn frequency(&self) -> f64 {
// Note -> freq
// Given a Midi note number `a`, get the frequency in Hz.
// The frequency doubles every 12 notes, and A440 = Midi n... | Rust | 0 |
# Copyright (c) 2023 PaddlePaddle 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 appli... | Python | 1 |
let mut s = String::new();
let start = self.current;
while let Some(n) = self.peek() {
if pred(n) {
match self.consume() {
Some(ch) => s.push(ch),
None => break,
}
} else {
break;
... | Rust | 0 |
add(self, y: An<Y>) -> Self::Output {
An(Binop::new(self.0, y.0, FrameAdd::new()))
}
}
/// `X + constant` binary operator: Adds `constant` to outputs of `X`.
/// Broadcasts `constant` to an arbitrary number of channels.
impl<X> std::ops::Add<f64> for An<X>
where
X: AudioNode<Sample = f64>,
X::Inpu... | Rust | 0 |
_all(&workspace);
let mut sink = WorkspaceSink::new(&workspace).unwrap();
// workspace is empty, check it!
assert_eq!(read_dir(&workspace).unwrap().count(), 0);
// populate workspace
let cs1 = example_constraints();
sink.push_constraints(cs1).unwrap();
// ensure there is exactly one file c... | Rust | 0 |
, false, false);
}
#[test]
fn regular_invalid_ttl_using_msg_test(){
let package = Package::RegularMsg{
topic: "".to_string(),
priority: 111,
content: vec![],
cash: false,
ttl: Some(10)
};
check_codec_correct(package, true, ... | Rust | 0 |
lt<(), Box<dyn std::error::Error>> {
let addr = "0.0.0.0:50051".parse()?;
let svc = UserServiceImpl {
cache: vec!(User {
uuid: "6daf4c42-7aa2-4a50-9d97-6b1c8956ac3a",
email: "<EMAIL>",
password_salt: "<PASSWORD>",
password_hash: "<PASSWORD>",
s... | Rust | 0 |
x23), SGray8::new(0), SGray8::new(0),
SGray8::new(0), SGray8::new(0xBB), SGray8::new(0xBB),
SGray8::new(0), SGray8::new(0xBB), SGray8::new(0xBB),
];
assert_eq!(r.pixels(), &v[..]);
}
#[test]
fn copy_color_srgb8() {
let mut r = Raster::<SRgb8>::with_clear(3, 3... | Rust | 0 |
def send_breakdown_response(self, breakdown, context):
self._send_message(breakdown, 'breakdown', context)
| Python | 1 |
ArrayView1<f64>) -> f64,
{
let mut func = utils::WrappedFunction { num: 0, func: func };
let mut x0 = Array1::<f64>::from_iter(args.iter().map(|&v| v as f64));
let n: usize = x0.len();
let adaptive = self.adaptive;
let maxiter: Option<usize>;
let maxfun: Option<usiz... | Rust | 0 |
ub async fn update(
path: web::Path<(String,)>,
data: web::Json<NoteTemplate>,
config: web::Data<Config>,
jwt: jwt::JWT,
db_pool: web::Data<DbPool>
) -> Result<HttpResponse, ApiError> {
let data: NoteTemplate = data.into_inner();
let conn = db_pool.get()?;
let claims: Claims = jwt::extra... | Rust | 0 |
sicSignupForm'}
DEFAULT_FROM_EMAIL = '-'
APSCHEDULER_DATETIME_FORMAT = "N j, Y, f:s a"
APSCHEDULER_RUN_NOW_TIMEOUT = 25
EMAIL_HOST = 'smtp.yandex.ru' # адрес сервера Яндекс-почты для всех один и тот же
EMAIL_PORT = 465 # порт smtp сервера тоже одинаковый
EMAIL_HOST_USER = '' # ваше имя пользователя, например, есл... | Python | 1 |
], [4, 8]])
connector = FromListConnector(pairs)
pre_slices = [Slice(0, 3), Slice(4, 6), Slice(7, 9)]
post_slices = [Slice(0, 2), Slice(3, 5), Slice(6, 9)]
pre_app_vertex = MockAppVertex(10, pre_slices)
post_app_vertex = MockAppVertex(10, post_slices)
pre_pop = MockPopulation(10, "Pre", pre_app_... | Python | 1 |
after_terminator() {
assert!(!has_flag::has_flag(
"unicorn",
_c_iter(vec!["--foo", "--", "--unicorn"])
))
}
#[test]
fn not_contain() {
assert!(!has_flag::has_flag(
"unicorn",
_c_iter(vec!["--foo"])
))
}
#[test]
fn default_short_prefix() {... | Rust | 0 |
9
DS_NAME_ERROR_NOT_FOUND, 8470
DS_NAME_ERROR_NOT_UNIQUE, 8471
DS_NAME_ERROR_NO_MAPPING, 8472
DS_NAME_ERROR_DOMAIN_ONLY, 8473
DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING, 8474
DS_CONSTRUCTED_ATT_MOD, 8475
DS_WRONG_OM_OBJ_CLASS, 8476
DS_DRA_REPL_PENDING, 8477
DS_DS_REQUIRED, 8478
DS_INVALID_LDAP_DISPLAY_NAM... | Rust | 0 |
import argparse
import cv2
import glob
import numpy as np
import os
import torch
from basicsr.archs.rrdbnet_arch import RRDBNet
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--model_path',
type=str,
default= # noqa: E251
'experiments/pretrained_models/E... | Python | 1 |
nicClient = dapr_v1::dapr_client::DaprClient<TonicChannel>;
impl<K> From<(K, Vec<u8>)> for common_v1::StateItem
where
K: Into<String>,
{
fn from((key, value): (K, Vec<u8>)) -> Self {
common_v1::StateItem {
key: key.into(),
value,
..Default::default()
}
}
... | Rust | 0 |
ROM Multi Bit Interrupt"]
#[inline(always)]
pub fn rommbe(&self) -> ROMMBE_R {
ROMMBE_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - ROM Single Bit Interrupt"]
#[inline(always)]
pub fn romsbe(&self) -> ROMSBE_R {
ROMSBE_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc ... | Rust | 0 |
StmtT::Assign(v, e) => StmtT::Assign(t.translate_var(v), e.translate(t)),
StmtT::Store(e1, e2, sz, spc) => {
StmtT::Store(e1.translate(t), e2.translate(t), sz, spc)
}
StmtT::Branch(bt) => StmtT::Branch(bt.translate(t)),
StmtT::CBranch(c, bt) =... | Rust | 0 |
ILENAME. This filename should be no more than eight characters to be compatible with NASTRAN.
""" # nopep8
return self._cards[2].get_value("mass")
@mass.setter
def mass(self, value: str) -> None:
"""Set the mass property."""
self._cards[2].set_value("mass", value)
@property... | Python | 1 |
s.push_str(&inner.to_string());
err = inner;
}
s
}
fn main() {
match run() {
Ok(()) => (),
Err(err) => {
eprintln!("{}", error_chain(err.as_ref()));
process::exit(1);
}
}
}
#![no_std]
#![no_main]
extern crate nrf52833_hal as hal;
use core::{c... | Rust | 0 |
rk. If the network is not stable for more than
a specific period (election_timeout * election_timeout_factor), the health
watcher automatically stops and a disaster recovery procedure should be staged.
"""
unstable_start_time = None
# Note: this currently does not detect one-way... | Python | 1 |
"""
Test that we can export a block from the runtime (to XML) and re-import it without error.
"""
import copy
from io import BytesIO
from .base import XBlockHandlerTestCase, scenario
from .test_team import TEAMSET_ID
class TestExportImport(XBlockHandlerTestCase):
@scenario('data/basic_scenario.xml')
def te... | Python | 1 |
: (optional) PCP Options :
: :
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
//! **Version**: Only version 2 is supported
//!
//! **R**: Indicates Request (0) or Response (1).
//!
//! *... | Rust | 0 |
]
#[doc(hidden)]
pub fn InvalidateSubFramebuffer_is_loaded(&self) -> bool {
!self.glInvalidateSubFramebuffer_p.load(RELAX).is_null()
}
/// [glIsBuffer](http://docs.gl/es3/glIsBuffer)(buffer)
#[cfg_attr(feature = "inline", inline)]
#[cfg_attr(feature = "inline_always", inline(always))]
... | Rust | 0 |
import torch
import torchaudio
from transformers import AutoFeatureExtractor, AutoModelForAudioClassification
MODEL_PATH = "D:/SER MiniProj/wav2vec2_model/"
TARGET_SAMPLE_RATE = 16000 # Model requires 16kHz audio
# Load feature extractor and model
feature_extractor = AutoFeatureExtractor.from_pretrained(MODEL_PATH)
... | Python | 1 |
/// ```text
/// U+11A8 ( ᆨ ) HANGUL JONGSEONG KIYEOK
/// U+11F9 ( ᇹ ) HANGUL JONGSEONG YEORINHIEUH
/// U+D7CB ( ퟋ ) HANGUL JONGSEONG NIEUN-RIEUL
/// U+D7FB ( ퟻ ) HANGUL JONGSEONG PHIEUPH-THIEUTH
/// ```
T {
abbr => T,
long => T,
human =... | Rust | 0 |
rain_ir::primitive::logical::Bool;
/// use rain_ir::typing::Type;
///
/// // Constants reside in the null region:
///
/// assert_eq!(true.clone_region(), Region::NULL);
/// assert_eq!(false.clone_region(), Region::NULL);
///
/// // Parameters reside in their region:
///
/// // W... | Rust | 0 |
p=[]
for n in range(18,1000):
a='2' +'5' * n
while '25' in a or '355' in a or '555' in a:
if '25' in a:
a= a.replace('25','5',1)
if '355' in a:
a= a.replace('355','52',1)
if '555' in a:
a= a.replace('555','3',1)
if a.count('3')==2:
p.append... | Python | 1 |
fs_ioctl<NativeArch>);
assert_eq_align!(kernel::usbdevfs_ioctl, usbdevfs_ioctl<NativeArch>);
#[repr(C)]
#[allow(non_snake_case)]
pub struct usbdevfs_ctrltransfer<Arch: Architecture> {
pub bRequestType: u8,
pub bRequest: u8,
pub wValue: u16,
pub wIndex: u16,
pub wLength: u16,
pub timeout: u32,
... | Rust | 0 |
# services/parsing_service.py
from transformers import pipeline
from services.preprocessing import temizle
from fastapi.encoders import jsonable_encoder
# NER pipeline oluştur
ner_model = pipeline(
task="ner",
model="savasy/bert-base-turkish-ner-cased",
tokenizer="savasy/bert-base-turkish-ner-cased",
... | Python | 1 |
u32) -> u32 {
let __autotrace_guard = ::holochain_tracing::push_span_with(|span| {
span.child("e in crates/tracing_macros/tests/macros.rs:53 (auto:fn)")
});
{
f(x) * 2
}
}
pub fn f(x: u32) -> u32 {
let __autotrace_guard = ::holochain_tracing::push... | Rust | 0 |
ers[i].time) * scale)/SCALE_PRECISION) as i32
}
}
fn compute_difficulty(headers: &Vec<BlockHeader>) ->Result<Vec<HeaderWithDifficulty>, util::Error> {
let mut headers_with : Vec<HeaderWithDifficulty> = vec!();
let mut height: usize = 0;
let max_target = max_target(Network::Bitcoin);
for i in 0 as ... | Rust | 0 |
import os
def parse_distributions_h(ffi, inc_dir):
"""
Parse distributions.h located in inc_dir for CFFI, filling in the ffi.cdef
Read the function declarations without the "#define ..." macros that will
be filled in when loading the library.
"""
with open(os.path.join(inc_dir, 'random', 'bi... | Python | 1 |
"""
Example Size Distribution Plots
-------------------------------
Example shows how to plot up CCN droplet count
in a size distribution plot. Also shows how to
add different plot types together using
assign_to_figure_axis.
Author: Adam Theisen
"""
from arm_test_data import DATASETS
import matplotlib.pyplot as pl... | Python | 1 |
# Copyright (c) 2015-2018, 2022 by Rocky Bernstein
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This prog... | Python | 1 |
) struct Owned {
/// Worker generation. This guards concurrent access to the `Owned` struct.
/// When a worker starts running, it checks that the generation it has
/// assigned matches the current generation. When it does, the worker has
/// obtained unique access to the struct. When it fails, another t... | Rust | 0 |
MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses Amino JSON and will be removed in the future
#[serde(rename = "mode", skip_serializing_if = "Option::is_none")]
pub mode: Option<Mode>,
}
impl CosmosTxV1beta1ModeInfoSingle {
pub fn new() -> CosmosTxV1beta1ModeInfoSingle {
CosmosTx... | Rust | 0 |
]
#[doc = " | :-- | :----------------- | :------------ | :----------------------------------- |"]
#[doc = " | 4 | `BR_SSLPRF_SHA256` | SHA-256 | Value matches `br_sha256_ID` |"]
#[doc = " | 5 | `BR_SSLPRF_SHA384` | SHA-384 | Value matches `br_sha384_ID` |"]
#[doc = ""]
#[doc ... | Rust | 0 |
, Clone)]
pub struct ActorsServiceDummy {}
impl ActorsServiceDummy {
pub fn new() -> Self {
Self {}
}
}
impl Default for ActorsServiceDummy {
fn default() -> Self {
Self::new()
}
}
impl ActorsService for ActorsServiceDummy {
fn send(&self, _: ActorsMessageTo) {}
fn try_recv(&... | Rust | 0 |
, PartialEq, Eq)]
pub struct Upsert {
pub index: Option<UpsertIndex>,
pub do_clause: UpsertDo,
pub next: Option<Box<Upsert>>,
}
impl ToTokens for Upsert {
fn to_tokens<S: TokenStream>(&self, s: &mut S) -> Result<(), S::Error> {
s.append(TK_ON, None)?;
s.append(TK_CONFLICT, None)?;
... | Rust | 0 |
r:
"""Return the latest version."""
return self.coordinator.data[DATA_KEY_CORE][ATTR_VERSION_LATEST]
@property
def installed_version(self) -> str:
"""Return the installed version."""
return self.coordinator.data[DATA_KEY_CORE][ATTR_VERSION]
@property
def entity_picture(... | Python | 1 |
###"
146..151: attempted to access a non-existent field in a struct.
268..273: attempted to access a non-existent field in a struct.
361..366: attempted to access a non-existent field in a struct.
451..452: attempted to access a field on a primitive type.
83..516 '{ ...ype. }': ()
93..96 'fo... | Rust | 0 |
}
// 演算子
"mul" => {
if args.len() == 2 {
let s = args[0].to_raw_integer()?;
let n = args[1].to_raw_integer()?;
Ok(MayObject::Integer(s * n))
} else {
Err(RuntimeError::ArgumentErr)
}
}
... | Rust | 0 |
from setuptools import find_packages, setup
def read_description():
with open('README.rst') as file:
return file.read()
if __name__ == '__main__':
setup(
name='mpire',
version='2.10.2',
author='Sybren Jansen',
description='A Python package for easy multiprocessing, bu... | Python | 1 |
zero(), a);
assert_eq!(a * fp_480::Fp480::zero(), fp_480::Fp480::zero());
}
#[test]
fn mul_precalc() {
// a = 95268205315236501484672006935066056413858283446892086784168052156537964209835102730449048569806878637400128131440203902086374553015554146305
let a = fp_480::Fp480::new([1u32... | Rust | 0 |
import contextlib
import datetime
from typing import Callable
from unittest import mock
import pytest
from freezegun import freeze_time
from streamlit.testing.v1.app_test import AppTest
from streamlit.testing.v1.element_tree import Block, Element
import demo.src.utils
from demo.src.demo_apps import simple_stqdm_in_ma... | Python | 1 |
T_THRESHOLD:.4f}")
# Ενημέρωση του trailing sell price
trailing_sell_price = highest_price * (1 - TRAILING_PROFIT_THRESHOLD)
trailing_sell_price = max(trailing_sell_price, active_trade)
... | Python | 1 |
!("final frequency: {}", total);
let first_multiple = first_multiple_freq(&contents);
println!("first repeated frequency: {}", first_multiple);
}
<reponame>jmetz93/rust-practice
// arrays - fixed list where elements are same type
use std::mem;
pub fn run() {
let mut numbers: [i32; 4] = [1, 2, 3, 4];
// w... | Rust | 0 |
SQS Developer Guide</i>.</p>
pub fn message_deduplication_id(&self) -> std::option::Option<&str> {
self.message_deduplication_id.as_deref()
}
/// <p>This parameter applies only to FIFO (first-in-first-out) queues.</p>
/// <p>The tag that specifies that a message belongs to a specific message gr... | Rust | 0 |
ext<355>>,
/// TradeInputSource
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "578")]
pub trade_input_source: Option<String>,
/// TradeInputDevice
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "579")]
pub trade_input_device: Option<String>,
/// Standard Message Trailer... | Rust | 0 |
nd(self,value,key=None):
""" Appends the vehicle mass, but only let's one ever exist. Keeps the newest one
Assumptions:
None
Source:
N/A
Inputs:
None
Outputs:
None
Properties Used:
N/A
"""
... | Python | 1 |
read_network_graph();
let params = ProbabilisticScoringParameters::default();
let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
}
fn generate_routes<S: Score>(
bench: &mut Bencher, graph: &NetworkGraph, mut scorer... | Rust | 0 |
# -*- coding: utf-8 -*-
# Copyright 2020 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... | Python | 1 |
xn_and_infos[first_version..=last_version].to_vec(),
None,
Some(first_version as u64),
first_proof,
last_proof,
)
};
// consensus_data_hash isn't used in proofs, but we need it to construct LedgerInfo.
... | Rust | 0 |
from rpmidi import RPMidi
from PicoGameBoy import PicoGameBoy
import time
from random import randint
import _thread
pgb=PicoGameBoy()
x=[0x91, 76, 69, 0x81, 76, 0, 0x91, 72, 64, 0x91, 74, 67, 0x91, 72, 65, 0x81, 72, 0, 0x81, 71, 0, 0x91, 57, 52, 0x81, 57, 0, 0x91, 57, 52, 0x81, 57, 0, 0x81, 76, 0, 0x91, 72, 64, 0x91, ... | Python | 1 |
/AccessibilityServiceInfo.html#flags)
pub fn set_flags<'env>(&'env self, value: i32) {
unsafe {
let env = __jni_bindgen::Env::from_ptr(self.0.env);
let (class, field) = env.require_class_field("android/accessibilityservice/AccessibilityServiceInfo\0", "flags\0", "I\0"... | Rust | 0 |
# main.py ── versión con temporizador
from torch_geometric.loader import DataLoader
from diffusion_model import (LightweightPetriDiffusion, train_model,
compute_edge_weights, compute_marginal_probs)
from petri_dataset import PetriNetDataset
import argparse, time, os, torch
def main(net_t... | Python | 1 |
netmask: Ipv4Addr) -> Interface {
let ipv4 = Ifv4Addr {
ip: addr,
netmask,
broadcast: None,
};
Interface {
name: "test-if".to_string(),
addr: IfAddr::V4(ipv4),
}
}
mod in_same_subnet {
use super::*;
#[... | Rust | 0 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import as _init
T = {}
T['TE_RESUME'] = 'int' #流重传方式
TERT_RESTART = 0 #从本交易日开始重传
TERT_RESUME = 1 #从上次收到的续传
TERT_QUICK = 2 #只传送登录后的流内容
T['ErrorID'] = 'int' #错误代码
T['ErrorMsg'] = 'char[81]' #错误信息
T['ExchangeID'] = 'char[9]' #交易所代码
T['ExchangeName'] = 'char[31]' #交... | Python | 1 |
["id"].as_str().context("id is not a string")?.to_owned();
let props_obj =
node["properties"].as_object_mut().context("properties is not an object")?;
if let Some(config_props) = configuration.get(&node_id) {
props_obj.extend(config_props.clone());
}
}
*pipeline... | Rust | 0 |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'formingMagicSquare' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY s as parameter.
#
def formingMagicSquare(s):
# Write your code here
magic_squares = [
[8... | Python | 1 |
name"]))
# red_data = create_train_data(name, seq_len, 1, "red")
# blue_data = create_train_data(name, seq_len, 1, "blue")
# logger.info("【{}】预测期号:{} 窗口大小:{}".format(name_path[name]["name"], int(current_number) + 1, seq_len))
# if name == "ssq":
# red_pred, red_name_list = get_red_ball_predict_r... | Python | 1 |
}
turn_data = {
"turn": game_state.current_turn,
"timestamp": datetime.now().isoformat(),
"results": serializable_results,
}
game_state.turn_history.append(turn_data)
def export_game_summary(self, game_state: GameState, output_path: Path) -... | Python | 1 |
unsafe {
let mut error = ptr::null_mut();
let _ = ffi::g_data_output_stream_put_string(self.to_glib_none().0, str.to_glib_none().0, cancellable.0, &mut error);
if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }
}
}
fn put_uint16<'a, P: Into<Option<&'... | Rust | 0 |
syntax().clone();
let RangeInfo { range, info: (name, def) } = find_name(db, &syntax, position)?;
let declaration = match def.kind {
NameKind::Macro(mac) => mac.to_nav(db),
NameKind::Field(field) => field.to_nav(db),
NameKind::AssocItem(assoc) => assoc.to_nav(db),
NameKind::Def(... | Rust | 0 |
"expected_outcome": "ожидаемый результат"
}}
],
"quality_monitoring": {{
"key_indicators": ["ключевой индикатор 1", "ключевой индикатор 2"],
"monitoring_frequency": "частота мониторинга",
"alert_thresholds": "пороговые значения д... | Python | 1 |
e": completion_time,
"score": score,
"cookie": cookie
}
def is_bandle_message(message_content: str) -> bool:
"""Checks if a message contains a Bandle score."""
return "bandle" in message_content.lower() and BANDLE_PATTERN.search(message_content) is not None
def is_gisnep_message(message_co... | Python | 1 |
ncoding(Not UTF8)",
};
write!(f, "{}", msg)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_rqrr() {
let grid = [
[
1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,
],
[
1, 0, 0, 0, 0, ... | Rust | 0 |
"""empty message
Revision ID: b489bd0d1bc2
Revises: fd7d43422dbb
Create Date: 2025-05-10 12:31:28.110567
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "b489bd0d1bc2"
down_revision: Union[str, None] = "fd7d43422dbb"
br... | Python | 1 |
from packed double-precision (64-bit) floating-point elements in a, and store the results in dst.
///
/// Rounding is done according to the rounding\[3:0\] parameter, which can be one of:
/// (_MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC) // round to nearest, and suppress exceptions
/// (_MM_FROUND_TO_NEG_INF |_... | Rust | 0 |
# Copyright 2009-2011 Ram Rachum.
# This program is distributed under the LGPL2.1 license.
'''
Testing module for `garlicsim.general_misc.abc_tools.abstract_static_method`.
'''
import sys
import nose
from garlicsim.general_misc.abc_tools import abstract_static_method
from garlicsim.general_misc.third_party import a... | Python | 1 |
fin_template = """
# RIL (Reliance Industries Limited) Financial Report
## Company Information
| Name | Ticker | Stock Price | Market Cap |
|---|---|---|---|
| {symbol} | 'RIL' | {currentPrice} ₹ | {marketCap} Cr ₹ |
---
## 🏛️ Basic Company Information :
[Summary in 4 bullets of {longBusinessSummary}]
### Compan... | Python | 1 |
if base_symbol == ticker or quote_symbol == ticker:
matching_pairs.append(pair)
if not matching_pairs:
raise ValueError(f"No pairs found for ticker: {ticker}")
# 3) Find the pair with the highest 24-hour volume
top_pair = None
max_volume = 0.0
... | Python | 1 |
/// The file to save the command history to
#[structopt(
long = "history-file",
parse(from_os_str),
default_value = "repl-history"
)]
pub history_file: PathBuf,
/// Files to preload into the REPL
#[structopt(name = "FILE", parse(from_os_str))]
pub files: Vec<PathBu... | Rust | 0 |
import torch
from torch.nn import functional as F
def calc_loc_loss(pred_loc: torch.Tensor,
test_loc: torch.Tensor,
cls_label: torch.Tensor,
use_smooth: bool = True
) -> torch.Tensor:
"""Compute location regression loss only on positive sampl... | Python | 1 |
lfway) = rounding::round_nearest(&mut fp, 6);
assert!(!above);
assert!(halfway);
assert_eq!(fp.mant, 1);
// Check above halfway (b'1100001')
let mut fp = float::ExtendedFloat {
mant: 0x61,
exp: 0,
};
let (above, halfway) = rounding::round_nearest(&mut fp, 6);
assert!(abo... | Rust | 0 |
"""
后端API适配新标签结构的代码修改示例
这些代码需要替换到 web/app.py 中的相应位置
"""
from flask import Flask, request, jsonify, session, redirect, url_for
from core.tag_manager import TagManager
from core.enhanced_tag_extractor import EnhancedTagExtractor
from core.response_generator import ResponseGenerator
import time
import uuid
# ===========... | Python | 1 |
from typing import Any
from nonebot import on_command
from nonebot.params import CommandArg, Arg
from nonebot.adapters.onebot.v11 import Message, GroupMessageEvent
from src.config import Config
from src.utils.permission import check_permission
from src.utils.generate import generate
from src.utils.database import db
... | Python | 1 |
_02)?, load_image(IMG_LCF3_03)?, load_image(IMG_LCF3_04)?, load_image(IMG_LCF3_05)?, load_image(IMG_LCF3_06)?]);
image_cache.insert((Stitch::Lcf3, Side::WS), vec![load_image(IMG_LCF3_01)?, load_image(IMG_LCF3_02)?, load_image(IMG_LCF3_03)?, load_image(IMG_LCF3_04)?, load_image(IMG_LCF3_05)?, load_image(IMG_LCF3_06)... | Rust | 0 |
let mut result = 0u8;
//which idx of row has the +/- 1
let idx0 = 0;
let idx1 = 0;
let idx2 = 0;
/* Get idx0,1,2 correct here */
result |= (idx0 << 0);
result |= (idx1 << 2);
result |= ((matrix[0][idx0 as usize] == -1.0) << 4);
result |= ... | Rust | 0 |
{}
for k, v in results_tr_tl.items():
current_i[k] = v[i]
max_key = max(current_i, key=current_i.get)
if max_key == gt_label or max_key == gt_label.lower():
logits_tr_tl_merge_results.append(1)
else:
... | Python | 1 |
2017_use_20250205_data_merge_label_FGSM_eps0.05測試_79_feature\\Inital_Local_weight_diff_client1_count.csv")
# list_
# list_ = df["dis_variation_Inital_Local"].head(10)
# list_ = df["dis_variation_Inital_Local"]
# 累加平均值計算
# 從第11個數字開始計算累加平均值(忽略前10個數字)
# 先過濾掉前10個數字
df_filtered = df["dis_variation_Inital_Local"][10:]
# 再過... | Python | 1 |
import asyncio
from fastapi import FastAPI
from contextlib import asynccontextmanager
from app.db.db_connection import create_tables
from app.routes.payment_routes import payment_router
from app.kafka.consumer import consume_events
from app.kafka.producer import KAFKA_PRODUCER, init_kafka_producer
# Lifespan context ma... | Python | 1 |
("Station 6");
///
/// track1.add_station("Station 7");
/// track2.add_station("Station 8");
/// track3.add_station("Station 9");
///
/// let mut track4 = track3.split();
/// let track5 = track4.split();
///
/// metro.add_station("Station 10 (Detached)");
///
/// track5.join(&track1);
///
/// track4.add_station("Statio... | Rust | 0 |
5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10"
)),
18216
);
}
}
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COP... | Rust | 0 |
"""
oauthlib.oauth1
~~~~~~~~~~~~~~
This module is a wrapper for the most recent implementation of OAuth 1.0 Client
and Server classes.
"""
from .rfc5849 import (
SIGNATURE_HMAC, SIGNATURE_HMAC_SHA1, SIGNATURE_HMAC_SHA256,
SIGNATURE_HMAC_SHA512, SIGNATURE_PLAINTEXT, SIGNATURE_RSA,
SIGNATURE_RSA_SHA1, SIGNAT... | Python | 1 |
onst VALIDATE_PROBLEM_FILE_FLAG: &str = "problem";
const VALIDATE_SOLUTION_FILE_FLAG: &str = "solution";
const DISLIKES_SUBCOMMAND: &str = "dislikes";
const DISLIKES_PROBLEM_FILE_FLAG: &str = "problem";
const DISLIKES_SOLUTION_FILE_FLAG: &str = "solution";
fn argument_config<'a, 'b>() -> App<'a, 'b> {
App::new("I... | Rust | 0 |
# [03] START: tests/test_modes_canon_config.py
from __future__ import annotations
from pathlib import Path
import pytest
from src.modes.profiles import get_profile
from src.modes.types import Mode
def test_canon_adds_required_sections(tmp_path: Path) -> None:
"""
_canon.yaml의 required가 없어도 Fallback require... | Python | 1 |
somewhat more
//! efficient. Note that this is solely a matter of performance, not
//! expressiveness.
//!
//! ### Skolemization
//!
//! For a discussion on skolemization and higher-ranked subtyping, please
//! see the module `middle::infer::higher_ranked::doc`.
<reponame>m-labs/ti2svd<gh_stars>10-100
#[doc = "Reader ... | Rust | 0 |
'Content-MD5': chunk_md5,
'Authorization': 'UpToken {}'.format(up_token)
}
)
if resp.ok() and ret:
part = _ResumeUploadV2Part(
part_no=chunk_info.chunk_no,
etag=ret.get('etag', '')
... | Python | 1 |
CounterWidgets::Button,
Button::build()
.labeled("Click the gooey cinnamon rolls!")
.on_clicked(events.map(|_| CounterEvent::ButtonClicked))
.image(Image::from(Asset::build().path(vec!["rolls.jpg"]).finish()))
.finish(),
... | Rust | 0 |
model=model,
loader=val_loader,
eval_criterion=eval_criterion,
device=device,
epoch=epoch,
epochs=epochs
)
# Evaluate EMA model
ema_val_loss, ema_val_acc = evaluate(
model=ema_model,
loader=val_loader,
... | Python | 1 |
eraldKill(HeraldKill),
BaronKill(BaronKill),
ChampionKill(ChampionKill),
Multikill(Multikill),
Ace(Ace),
}
#[derive(Deserialize, Debug, Clone, PartialEq)]
pub struct GameStart {
#[serde(rename = "EventID")]
pub event_id: usize,
#[serde(rename = "EventTime")]
pub event_time: f64, // TODO... | Rust | 0 |
import os
from passlib.context import CryptContext
from datetime import datetime, timedelta
from typing import Union, Any
import jwt
from decouple import config
ACCESS_TOKEN_EXPIRE_MINUTES = 30 # 30 minutes
REFRESH_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7 days
ALGORITHM = config("JWT_ALGORITHM")
JWT_SECRET_KEY = confi... | Python | 1 |
ndroid.support.v7.widget.'
'RecyclerView/android.widget.LinearLayout/android.widget.LinearLayout[1]/android.widget.'
'LinearLayout/android.widget.Button'
)))
except NoSuchElementException:
return False
return True
... | Python | 1 |
ault());
let mut handler = IoHandler::new();
handler.extend_with(client.to_delegate());
let sample = handler.handle_request_sync(&(r#"
{
"jsonrpc": "2.0",
"method": "getblocktemplate",
"params": [{}],
"id": 1
}"#)).unwrap();
// direct hash is 010000000000000000000000000000000000000000000... | Rust | 0 |
let image = "wolfgangwazzlestrauss/cross-sampitor";
for entry in fs::read_dir("docker").unwrap() {
let path = entry.unwrap().path();
let target = path.extension().unwrap().to_str().unwrap();
let tag = format!("{}:{}", image, target);
let path_str = path.into_os_string()... | Rust | 0 |
"\t".repeat(indent), comment)?;
Ok(())
}
fn write_comments(w: &mut dyn Write, indent: usize, comments: &Vec<String>) -> std::io::Result<()> {
writeln!(w, "{}/**", "\t".repeat(indent))?;
for c in comments {
write_comment(w, indent, &c)?;
}
writeln!(w, "{} */", "\t".repeat(indent))?;
Ok((... | Rust | 0 |
crate::verification::MethodQuery;
use crate::verification::MethodRef;
use crate::verification::MethodScope;
use crate::verification::MethodWrap;
const ERR_VMNF: &str = "Verification Method Not Found";
const ERR_MI: &str = "Missing `id`";
/// A DID Document Service
#[derive(Clone, Debug, PartialEq, Deserialize, Serial... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.