text string | label_name string | labels int64 |
|---|---|---|
[feature(test)]
extern crate test;
use aead::{generic_array::GenericArray, AeadInPlace, NewAead};
use hex_literal::hex;
use kuznyechik::Kuznyechik;
use mgm::Mgm;
use test::Bencher;
#[rustfmt::skip]
const KEY: [u8; 32] = hex!("
<KEY>
<KEY>
");
#[rustfmt::skip]
const NONCE: [u8; 16] = hex!("
112233445566770... | Rust | 0 |
"""
Enhanced Research Service with SearXNG and Deep Content Analysis
This service integrates multiple search providers (Tavily, SearXNG) with deep content
extraction and analysis using LangChain and BeautifulSoup for comprehensive research.
"""
import asyncio
import logging
import time
from datetime import datetime
f... | Python | 1 |
from vpython import *
场景 = canvas(title="质点运动形成波\n", width=800, height=600, background=color.white)
def 更新标签():
球数文本.text = f"球数量: {球数.value}"
振幅文本.text = f"振幅: {振幅.value}\n"
角速度文本.text = f"角速度: {角速度.value:.2f}"
波速文本.text = f"波速: {波速.value}\n"
波长文本.text = f"波长: {2 * pi * 波速.value / 角速度.value:.2f}"... | Python | 1 |
_raw_data: MulByteView<'a, u32, LitEnd>,
pub ptr_to_raw_data: MulByteView<'a, u32, LitEnd>,
pub ptr_to_relocs: MulByteView<'a, u32, LitEnd>,
pub ptr_to_line_nums: MulByteView<'a, u32, LitEnd>,
pub num_of_relocs: MulByteView<'a, u16, LitEnd>,
pub num_of_line_nums: MulByteView<'a, u16, LitEnd>,
... | Rust | 0 |
ow)
self.actionURL.setEnabled(False)
self.actionURL.setObjectName("actionURL")
self.menuFile.addAction(self.actionNew)
self.menuFile.addSeparator()
self.menuFile.addAction(self.actionExit)
self.menuAuthentication.addAction(self.actionConf)
self.menuAuthentication.... | Python | 1 |
r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
... | Rust | 0 |
"token": "{token}",
"debug": false,
"heartInterval": 30000,
"reconnectInterval": 3000
}}
],
"plugins": []
}},
"musicSignUrl": "",
"enableLocalFile2Url": false,
"parseMultMsg": false
}}
""".strip()
@router.post("/restart")
@require_role(Role.Admin)
async def restart(_curr... | Python | 1 |
import pytest, sys
from asyncio import run
from fontgoggles.font import getOpener
from fontgoggles.misc.textInfo import TextInfo
from fontgoggles.misc.platform import setUseCocoa, getUseCocoa
from testSupport import getFontPath
from fontTools.pens.recordingPen import RecordingPen
font_paths = [
"MutatorSans.ttf",... | Python | 1 |
ArrayLen<<Diff<UInt<UInt<UInt<U, Ba>, Bb>, Bc>, U1> as ArrayLen<T>>::Array>,
Matrix<T,
Diff<UInt<UInt<UInt<U, Ba>, Bb>, Bc>, U1>,
Diff<UInt<UInt<UInt<U, Ba>, Bb>, Bc>, U1>>: Determinant<Output = T>,
{
type Output = T;
fn cofactor(&self, (i, j): MatrixIdx) -> T {
le... | Rust | 0 |
nStrategy(window=self.trend_window)
self.add_user_to_db(self.player.user_id, initial_balance, "MeanReversion")
self.users.append(self.player) # 确保添加到用户列表
except mysql.connector.Error as err:
print(f"加载用户信息失败: {err}")
def load_user_holdings_from_db(self, user):
... | Python | 1 |
r):
m = mRNNModel(is_training=True,
num_steps=config.buckets[0],
config=config,
model_name=FLAGS.model_name,
flag_with_saver=True,
model_root=FLAGS.model_root)
models.append(m)
with tf.variable_scope("mRNNmodel", reuse=True):
for bucket in ... | Python | 1 |
poll_fn(move |_| {
let needed_services = 0;
p2p.poll_events("bitcoin", needed_services, &mut cex);
Async::Ready(())
})).expect("can not spawn bitcoin event loop");
}
}
#[derive(Clone)]
struct KeepConnected {
cex: ThreadPool,
dns: Vec<SocketAddr>,
db: SharedDB... | Rust | 0 |
.child(html!("module-settings-bubble", {
.property("slot", "bubble")
.child(html!("module-settings-bubble-content", {
.property("kind", state.kind.as_str_id())
.property_signal("value", state.value.as_ref().unwrap_ji().... | Rust | 0 |
.and_then(|l| l.character_by_export_name(name.as_str()));
if let Some(Character::Bitmap(bitmap_object)) = character {
if let Some(bitmap) = renderer.get_bitmap_pixels(bitmap_object.bitmap_handle()) {
let new_bitmap_data = BitmapDataObject::empty_object(
activation.contex... | Rust | 0 |
prop_assert_eq!(actual_sb, expected_sb.try_into().unwrap());
}
}
}
}
#[macro_use]
extern crate rutie;
use rutie::{Class, Object, Hash, RString, AnyObject};
class!(JPath);
methods!(
JPath,
_rtself,
fn jp_say_rust_hello() -> Hash {
let mut hash = Hash::new();
... | Rust | 0 |
== list_index {
abs_index = Some(abs_idx);
list.push('>');
push_entry(&mut list, entry.as_ref(), remaining_cols);
} else if search_results.peek().is_none() && list_index > list_idx {
// if list_index outside of the displayable range
// -> display the ... | Rust | 0 |
from pyglet.text import Label
from pyglet.text import Label
from recomm_town.common import Vec
from recomm_town.draw.consts import (
ACTIVITY_CFG,
DASHBOARD_FONTS,
DASHBOARD_WHITE,
)
from recomm_town.human.activity import Activity
from recomm_town.shaders.arc import Arc
from recomm_town.shaders.sprite impo... | Python | 1 |
class Solution:
def arithmeticTriplets(self, nums: List[int], diff: int) -> int:
kMax = 200
ans = 0
count = [False] * (kMax + 1)
for num in nums:
if num >= 2 * diff and count[num - diff] and count[num - 2 * diff]:
ans += 1
count[num] = True
return ans
| Python | 1 |
atch *v {
some(ref i) => {
unsafe {
impure(*i);
}
}
none => {
}
}
}
fn main() {
}
// https://leetcode.com/problems/logger-rate-limiter/
#![allow(dead_code)]
use std::cell::RefCell;
use std::collections::HashMap;
#[derive(Default)]
struct Logger {
bucket: R... | Rust | 0 |
import streamlit as st
about_page =st.Page(
page="views/about_me.py",
title="About Me",
icon =":material/account_circle:",
default=True,
)
project_1_page=st.Page(
page="views/sales_dashboard.py",
title="Sales Dashboard",
icon=":material/bar_chart:",
)
project_2_page=st.Page(
page="vie... | Python | 1 |
= axs[0, 3].get_gridspec()
# for ax in axs[0:2, 2]:
# ax.remove()
# for ax in axs[0:2, 3]:
# ax.remove()
# axform1 = fig.add_subplot(gs[0:2, 2:3])
# axform2 = fig.add_subplot(gs[0:2, 3:4])
fig = plt.figure(constrained_layout=True)
figsize = (textwidth, 5.)
fig.set_size_inches(*figsize)
gs = GridSpec(6, 8, figu... | Python | 1 |
ate.
pub type Version = u64; // Height - also used for MVCC in StateDB
// In StateDB, things readable by the genesis transaction are under this version.
pub const PRE_GENESIS_VERSION: Version = u64::max_value();
use writedown;
pub mod html {
use writedown::{ast, Render};
//TODO: implement by macro
// as... | Rust | 0 |
_angle_and_ratio,
refine_bound,
ref_image_selected_tab,
cloth_uuid,
max_train_steps,
],
outputs=[infer_progress, tryon_output_images, template_mask, reference_m... | Python | 1 |
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
import src.users.service as service
from src.admins.schemas import Admin
from src.database import get_db
from src.users.schemas import UserCreate, UserResponse, UserModify, UsersResponse
... | Python | 1 |
d\xd4\xf3\x0b\xedU^\xfb\xdb{\x86\xc1\xe7\xcd\
\xd3\xc0\x08tuq\xe3\x06Lk\x08b\xaa~\x11\x11\
\x86\xbb#\x06\xc4\xdc\x11k\xf0\xd3;\x22{c\xd3\x1c\
\xe8\xe95f\xf4jm\xe5\xb6\xb3\xa25\x07\xf5\xbc\xfb\
\xccH\x87^\x97\xb9\xdf\x0ak\xc6\xdeO\xfa\xff\xc1\x03\
\xdc%\x84\xaa@\x01\xf4$\x00Sg9\xd2n\xeeU\
\xd5\xcd\xd8\xfb\x0f45\xf1\x1e\... | Python | 1 |
transparent::{self, TxIn, TxOut},
},
sighash::{signature_hash_data, SignableInput, SIGHASH_ALL},
util::sha256d::{HashReader, HashWriter},
};
#[cfg(feature = "zfuture")]
use self::components::tze;
pub mod builder;
pub mod components;
pub mod sighash;
pub mod util;
#[cfg(test)]
mod tests;
const O... | Rust | 0 |
cfg(any(feature = "word8", feature = "word16"))]
{
assert_eq!(size_of::<Mantissa2<P9>>(), 2);
assert_eq!(size_of::<Mantissa2<P12>>(), 2);
assert_eq!(size_of::<Mantissa2<P16>>(), 2);
}
#[cfg(not(any(feature = "word8", feature = "word16")))]
{
... | Rust | 0 |
GE', '6JZ', '15P', 'PE3', 'XPE',
'7PE', 'M2M', '13P', '3PP', 'PX4', '3OL', 'OC9', 'AE3',
'211', 'ODI', 'DIA', 'PG5', 'CXE', 'ME2', 'P4G', 'TOE',
'PE8', 'ZPG', 'MXE', 'MPO', 'NHE', 'CXS', 'T3A', '3CX',
'3FX', 'PIN', 'MGD', 'NAD', 'NAP', 'NDP', '... | Python | 1 |
ool {
**self == WP4_A::WP4_0
}
#[doc = "Checks if the value of the field is `WP4_1`"]
#[inline(always)]
pub fn is_wp4_1(&self) -> bool {
**self == WP4_A::WP4_1
}
}
impl core::ops::Deref for WP4_R {
type Target = crate::FieldReader<bool, WP4_A>;
#[inline(always)]
fn deref(... | Rust | 0 |
-> Option<Tool> {
let (bin_path, host_dylib_path, lib_path, include_path) =
vs15plus_vc_paths(target, instance)?;
let tool_path = bin_path.join(tool);
if !tool_path.exists() {
return None;
};
let mut tool = MsvcTool::new(tool_path);
tool.path.pus... | Rust | 0 |
,
}
impl MONRDYR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the fiel... | Rust | 0 |
2(&[[3.0, 1.0, 1.0], [1.0, 3.0, 1.0], [1.0, 1.0, 3.0]]);
let (e, vecs): (Array1<_>, Array2<_>) = (&a).eigh(UPLO::Upper).unwrap();
let s = vecs.t().dot(&a).dot(&vecs);
for i in 0..3 {
assert_rclose!(e[i], s[(i, i)], 1e-7);
}
}
#[test]
fn ssqrt() {
let a: Array2<f64> = random_hpd(3);
let ... | Rust | 0 |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
Wasserstein Distance (Optimal Transport)
"""
import torch
from torch.nn import functional as F
def cost_matrix_cosine(x, y, eps=1e-5):
""" Compute cosine distnace across every pairs of x, y (batched)
[B, L_x, D] [B, L_y, D] -> [B, Lx, L... | Python | 1 |
_c3.csv", csv).expect("Failed to write file");
}
tsf_close(tsf);
}
}
}<filename>src/events/message.rs
use crate::log_error;
use crate::{attachment_logging, db::note::NoteType};
use anyhow::bail;
use chrono::Utc;
use itertools::Itertools;
use maplit::hashmap;
use regex::Regex;
use se... | Rust | 0 |
ing.assert_array_almost_equal(td.get_descriptor().todoublearray(), l)
# Modifying an element of the list reflects in qr.descriptors
td_set[0][0] += 10
self.assertAlmostEqual(qr.descriptors[0][0], td_set[0][0])
# But changing the list itself shouldn't
self.assertEqual(len(qr.des... | Python | 1 |
get_gpu_memory_usage(),
][-1],
api_name = 'empty-cache',
)
with gr.Accordion('Run any code', open = False, visible = DEV_MODE):
gr.Markdown('''
The following input box allows you to execute arbitrary Python code. ⚠️ DON’T USE THIS FEATURE IF Y... | Python | 1 |
from openai import AsyncOpenAI
from typing import Union
from fastapi.responses import StreamingResponse
from ...database import KeyManager
from ...responses import streaming_chat_response, normal_chat_response
from ...utils import handle_errors
class OpenRouter:
"""
Default OpenRouter provider
"""
... | Python | 1 |
s(self, ctx):
super(HangarConsumableSlotContextMenu, self)._initFlashValues(ctx)
self._slotsCount = self._getVehicleItems().installed.getCapacity()
def _putOnAction(self, onId):
copyVehicle = self._getCopyVehicle()
copyVehicle.consumables.setLayout(*copyVehicle.consumables.installed... | Python | 1 |
= source_match.group(1)
corresponding_text_match = re.search(r'"corresponding_text":\s*"([^"]+)"', text)
if corresponding_text_match:
result_dict["corresponding_text"] = corresponding_text_match.group(1)
time_cost_match = re.search(r'"time_cost":\s*"([^"]+)"', text)
if time_cost_match:
... | Python | 1 |
nding and future IO to
/// return immediately with an appropriate value.
pub fn shutdown_all(&self) -> IoResult<()> {
self.stream.as_tcp().shutdown(Shutdown::Both)
}
}
/// A Sender that wraps a Writer and provides a default implementation using
/// DataFrames and Messages.
pub struct Sender {
mask: bool,
}
impl... | Rust | 0 |
3, 4, 5, 6];
let mut result = vec.clone();
let func = |t| {
match t % 3 {
0 => (0..0),
1 => (0..1),
_ => (0..2),
}
.map(move |n| t + n)
};
result.flat_map_inplace(&func);
let mut expected = vec.into_iter().flat_map(func).collect::<Vec<_>>()... | Rust | 0 |
clear::All);
let number = 600851475143; //6857
//let number = 600716379584; //9227
//let number = 13195; //29
let result = find_largest_prime_factor_of(number);
println!("003: The largest prime factor of {} is: {:?}", number, result);
}
fn find_largest_prime_factor_of(number: i64) -> i64 {
l... | Rust | 0 |
"build"];
let is_successful = std::process::Command::new("cmake")
.current_dir(fs::canonicalize(&REPO_DIR)?)
.args(cmd_args)
.status()?
.success();
if !is_successful {
return Err(format!("Failed: cmake {}", cmd_args.join(" ")).into());
}
Ok(())
}
/// Expects `g... | Rust | 0 |
)];
#[forbid(deprecated_pattern)];
use core::cmp::Eq;
use map::{hashmap, str_hash};
use io::{Reader, ReaderUtil};
use dvec::DVec;
use from_str::FromStr;
use result::{Err, Ok};
use to_str::ToStr;
export Url, Query;
export from_str, to_str;
export get_scheme;
export query_to_str;
export encode, decode;
export encode_c... | Rust | 0 |
ately./n/n' + copyrightMessage)
parser.add_argument('-inputCSV', type=str, help = 'The absolute, comma-separated paths of labels that need to be fused', required=True)
parser.add_argument('-outputDir', type=str, help = 'The output file to write the results', required=True)
args = parser.parse_args()
outputDir_... | Python | 1 |
#!/usr/bin/env python
from subprocess import call
from revutils import *
import random
from Crypto.Cipher import DES
def key_to_hex(s):
keystring = "{0:056b}".format(s)
string = ""
for i in range(8):
string += chr(int(keystring[i*7:((i+1)*7)], 2))
return string
bin1 = "01111111100010111110111... | Python | 1 |
import unittest
from lexer import Lexer
from sunda_parser import Parser
from interpreter import Interpreter
class SundaLanguageTest(unittest.TestCase):
def test_tokenization(self):
code = 'ngadeklarasikeun x = 5; tampilkeun x;'
lexer = Lexer(code)
tokens = list(lexer.tokenize())
se... | Python | 1 |
GR format, [23:0] B:G:R little endian
Bgr888 = 0x34324742,
/// 32-bit xBGR format, [31:0] x:B:G:R 8:8:8:8 little endian
Xbgr8888 = 0x34324258,
/// 32-bit RGBx format, [31:0] R:G:B:x 8:8:8:8 little endian
Rgbx8888 = 0x34325852,
/// 32-bit BGRx format, [31:0] B:G:R:x 8:8:8:... | Rust | 0 |
# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/gui/Scaleform/daapi/view/lobby/hangar/carousels/epicBattle/carousel_filter.py
from account_helpers.AccountSettings import EPICBATTLE_CAROUSEL_FILTER_1, EPICBATTLE_CAROUSEL_FILTER_2, EPICBATTLE_CAROUSEL_FILTER_CLIENT_1, EPICBATTLE_CA... | Python | 1 |
from _pydevd_bundle.pydevd_constants import USE_CYTHON_FLAG, ENV_TRUE_LOWER_VALUES, ENV_FALSE_LOWER_VALUES, IS_PY312_OR_GREATER
if IS_PY312_OR_GREATER:
if USE_CYTHON_FLAG in ENV_TRUE_LOWER_VALUES:
from ._pydevd_sys_monitoring_cython import *
elif USE_CYTHON_FLAG in ENV_FALSE_LOWER_VALUES:
from... | Python | 1 |
:30-5:31
body: VAR @ 5:35-5:36
var: x @ 5:35-5:36
"###);
}
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
use faf::const_concat_bytes;
use faf::const_config::*;
use faf::const_http::*;
use faf::extern_http_date;
use faf::util::{const_len, memcmp};
const ROU... | Rust | 0 |
tem>>,
/// Total number of items available.
#[serde(rename = "total")]
pub total: Option<i32>,
}
<gh_stars>0
/*
* Copyright 2019 <NAME>
*
* 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 L... | Rust | 0 |
-> bool {
*self == CH2OCR::_1
}
}
#[doc = "Possible values of the field `CH3OC`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CH3OCR {
#[doc = "The channel output is not affected by software output control."]
_0,
#[doc = "The channel output is affected by software output control."]
_1... | Rust | 0 |
import json
def add_resume_to_vector_db(resume_id: str, category: str, resume_text: str, **kwargs):
import chromadb
from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction
from app.core.settings import settings
embedding_function = OpenAIEmbeddingFunction(
api_key=settings.llm... | Python | 1 |
.msg)
def range_pop(self):
_nvtx.rangePop()
class RangePushHandler:
"""
At a specific event, pushes a range onto a stack of nested range span.
Stores zero-based depth of the range that is started.
Args:
msg: ASCII message to associate with range
"""
def __init__(self, ev... | Python | 1 |
let c = map.get(&location);
match c {
Some('a'..='z') => {
routes.insert(*c.unwrap(), (distance, doors.clone()));
},
Some('A'..='Z') => {
let mut lower = *c.unwrap();
lower.make_ascii_lowercase();... | Rust | 0 |
armup_steps:
sched = (k+1) / warmup_steps
else:
sched = 1.0
lr = group['lr']*sched
group['scheduled_lr'] = lr # For logging purposes
weight_lr_power = group['weight_lr_power']
r = group['r']
lr_max = group[... | Python | 1 |
Cat,
}
fn main() {
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open("pet_owner.json")
.expect("failed to create JSON file");
let buf_writer = BufWriter::new(&file);
write_json(buf_writer).expect("Failed to write JSON");
... | Rust | 0 |
"dns#resourceRecordSet".
name: For example, www.example.com.
rrdatas: As defined in RFC 1035 (section 5) and RFC 1034 (section 3.6.1).
ttl: Number of seconds that this ResourceRecordSet can be cached by
resolvers.
type: The identifier of a supported record type, for example, A, AAAA, MX,
... | Python | 1 |
, 0, 0, 0, 0, 0);
}
#[test]
#[should_panic]
fn put_pixel_out_of_bounds_y_should_panic() {
let pixbuf = Pixbuf::new(Colorspace::Rgb, true, 8, 100, 200).unwrap();
pixbuf.put_pixel(0, 200, 0, 0, 0, 0);
}
#[test]
#[should_panic]
fn too_small_slice_should_panic() {
let data = vec![0u8; 100 * 99 * 4];
Pix... | Rust | 0 |
# A happy string is a string that:
# consists only of letters of the set ['a', 'b', 'c'].
# s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).
# For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
# Gi... | Python | 1 |
import sqlite3
conn = sqlite3.connect("qly_nhan_vien.db")
cursor = conn.cursor()
#Tạo bảng PHONG:
cursor.execute("""
CREATE TABLE IF NOT EXISTS PHONG (
Id INTEGER PRIMARY KEY,
Name TEXT NOT NULL
)
""")
#Tạo bảng NHAN_VIEN:
cursor.execute("""
CREATE TABLE IF NOT EXISTS NHAN_VIEN (
id INTEGER PRIMARY KEY,
... | Python | 1 |
&mut pubkey,
)
};
match error_code {
0 => {
let str_list = unsafe { collect_multi_cstring_and_free(&[address, pubkey]) }?;
let addr_obj = &str_list[0];
let pubkey_obj = &str_list[1];
... | Rust | 0 |
the field 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 << 6)) | (((value as u32) & 0x01) << 6);
... | Rust | 0 |
let ab = b - a;
let ac = c - a;
Triangle {
a: a,
ab: ab,
ac: ac,
normals: normals,
}
}
fn local_coordinates(&self, point: Point) -> (f64, f64, f64) {
let ort_ac = self.ac.cross(self.normal());
let ort_ab = self.ab.cross(sel... | Rust | 0 |
r_recovered.get_y().clone(),
&rescue_params,
)?;
Ok(AllocatedSignerPubkey {
pubkey,
point: r_recovered,
is_correctly_unpacked: is_r_correct,
r_x_bit: Boolean::from(r_x_bit),
r_y_bits: r_y.get_bits_be(),
})
}
pub fn verify_circuit_signature<E: RescueEngine + ... | Rust | 0 |
s],[0,1]) # adds the same cross section to the start and finish of the branch
# b_ps = branch()
# ## Note, you can use this one or
# b_ps.setup_pattern_close_loop(nloops=5,filletR=10,return_gap=15)
# b_ps.add_cross_section([cs,cs],[0,1]) # adds the same cross section to the start and ... | Python | 1 |
types.Content(
role="user",
parts=[
types.Part(
text=_TEST_QUERY_PROMPT,
)
],
)
],
),
... | Python | 1 |
from pynput import keyboard
import os
# Define the file path
file_path = os.path.join(os.environ["USERPROFILE"], "Documents", "output.txt")
# Function to clear the contents of the output file
def clear_output_file():
with open(file_path, 'w') as f:
f.write('')
# Set to keep track of pressed keys
pressed_... | Python | 1 |
10
// – and from around 18h to 36h when WUCKSEL[2:1] = 11. In this last case 216 is
// added to the 16-bit counter current value.When the initialization sequence is
// complete (see Programming the wakeup timer on page 781), the timer starts
// counting down.When the wakeup function is ... | Rust | 0 |
. Control line input volume.
pub struct Invol<CHANNEL> {
cmd: LineIn<CHANNEL>,
}
impl<CHANNEL> Invol<CHANNEL> {
impl_bits!(LineIn<CHANNEL>, 5, 0);
///Set volume from a dB representation.
pub fn db(mut self, volume: InVoldB) -> LineIn<CHANNEL> {
let mask = !((!0) << 5);
self.cmd.data = s... | Rust | 0 |
w_size
d["initial_states"] = list(map(lambda x: x.to_dict(), self.initial_states))
d["state_transitions"] = list(map(lambda x: (x[0].to_dict(), x[1].to_dict(), x[2].to_dict(), x[3].to_dict()),
self.state_transitions))
d["emulation_name"] = self.emulation... | Python | 1 |
from marshmallow import Schema, fields
class PortfolioSchema(Schema):
""" Define como uma ordem de cliente deverá ser retornado
"""
symbol = fields.Str()
quantity = fields.Float()
price = fields.Float()
portfolio_schema = PortfolioSchema()
portfolios_schema = PortfolioSchema(many=True) | Python | 1 |
mod async_tokio;
pub use self::async_tokio::TokioTun;
}
}
<filename>contract/src/internal.rs
use crate::*;
pub(crate) fn assert_one_yocto() {
assert_eq!(
env::attached_deposit(),
1,
"Requires attached deposit of exactly 1 yoctoNEAR"
)
}
// Copyright (c) Facebook, Inc... | Rust | 0 |
"-17:51:04.78", 0).unwrap(),
-175105.0,
),
];
for (input, expect) in cs {
let mut ctx = EvalContext::default();
let r = cast_any_as_any::<Duration, Real>(&mut ctx, Some(&input));
let r = r.map(|x| x.map(|x| x.into_inner()));
let... | Rust | 0 |
from __future__ import division, print_function, absolute_import
import os, sys, datetime
import numpy as np
import tensorflow as tf
import copy
import pdb
from model.instance_model import DATA_LEN_IMAGENET_FULL
def tuple_get_one(x):
if isinstance(x, tuple) or isinstance(x, list):
return x[0]
return x... | Python | 1 |
as usize;
if light_count > per_view_data.point_lights.len() {
break;
}
let out = &mut per_view_data.point_lights[light_count];
out.position_ws = light.position.position.into();
out.position_vs = (view.view_matrix() * light.position.position.e... | Rust | 0 |
j in (0..N::dim_hidden() + 1) {
state.doutput[j][i] = X::LearningRate::lrate() *
nn.node(Node::Hidden(j)) * state.eoutput[i] +
X::MomentumConstant::momentum() * state.doutput[j][i];
}
}
for i in (0..N::dim_hidden()) {
let wsum = (0..N::dim_output()).fold(
0f64,
|acc, j... | Rust | 0 |
results = calculate_f1_em_bleu(dataset, predictions)
f1_total, em_total, bleu_total = 0.0,0.0,0.0
total_num = 0
for lang in results:
f1_total += results[lang]["f1"]
em_total += results[lang]["em"]
bleu_total += results[lang]["bleu"]
total_num += results[lang]["count"]... | Python | 1 |
# (C) 2025 A.Voß, a.voss@fh-aachen.de, info@codebasedlearning.dev
"""
This snippet is about accessing Microsoft Exchange Services.
Teaching focus
- read emails
- send email
Preparations
- .env file with credentials, not part of the project; entries e.g.,
EXCHANGE_USER_NAME=xy1234z
- virtual environme... | Python | 1 |
impl std::fmt::Display for ClientInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}!{}@{}", self.nick, self.user, self.host)
}
}
impl ClientInfo {
fn echo_back(&self, command: Command) -> Message {
Message {
tags: None,
prefix:... | Rust | 0 |
[-1]*p:shape_port[-1]*(p+1)]
extent = shape_port[1]
else:
Zdist = dist_m
extent = shape_port[0]
#levels = [0.5,0.75,1.25,1.5,1.75,2,3]
fig = plt.figure()
plt.subplot(2,1,1)
ax = plt.gca()
plt.imshow(np.vstack((np.flipud(dat_port), dat_star)), cmap='gray',extent=[min(Zdist), max(Zdi... | Python | 1 |
from openchem.models.openchem_model import OpenChemModel
import torch
class Graph2Label(OpenChemModel):
r"""
Creates a model that predicts one or multiple labels given object of
class graph as input. Consists of 'graph convolution neural network
encoder'__, followed by 'graph max pooling layer'__ and... | Python | 1 |
let mut score = 0.0;
score -= board.home_bases[players.0 as usize].pieces_waiting as f64 * 2.0;
score -= board.home_bases[players.1 as usize].pieces_waiting as f64 * 2.0;
for (player, pieces) in &[(players.0, a_pieces), (players.1, b_pieces)] {
for piece in pieces.iter() {
match piece ... | Rust | 0 |
return types_pb2.PRIMITIVE_BOOL
elif p == datetime:
return types_pb2.PRIMITIVE_TIMESTAMP
elif p == List[str]:
return types_pb2.PRIMITIVE_STRING_LIST
elif p == List[int]:
return types_pb2.PRIMITIVE_INTEGER_LIST
elif p == List[float]:
r... | Python | 1 |
// 원하는 dimension의 random vector를 선언. 이때 random number는 uniform dist.
// rng : random number generator
// dim : dimension of random vector
let mut buff : Vec<f64> = vec![0f64; dim];
for x in &mut buff{
*x = rng.sample(Open01);
}
return Position::<f64>::new(buff);
}
pub fn get_unifo... | Rust | 0 |
.
pub(crate) fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] {
match stmt.node {
ast::StmtKind::Local(ref local) => &local.attrs,
ast::StmtKind::Item(ref item) => &item.attrs,
ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => &expr.attrs,
ast::StmtKind::M... | Rust | 0 |
#!/usr/bin/env python3
#
# Copyright (c) 2010 - 2025, Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following co... | Python | 1 |
#V8版本特征:交叉转化次数
from collections import Counter
import pandas as pd
import numpy as np
#对训练集进行分割以用于后续的窗口计算
def cutTrain():
print('开始载入')
df_train=pd.read_csv('data/merge/train_m_base.csv')
chunck=len(df_train)//5
for i in range(5):
print('处理第%d份数据'%(i+1))
if i!=4:
... | Python | 1 |
, twin::Twin::new(2.0_f32,0.0).sqrt());
println!("{:?}", twin::Twin::new(2.0_f32,0.0).sqrt().sqr());
println!("{:?}", twin::Twin::new(2.0_f64,0.0).sqrt());
println!("{:?}", twin::Twin::new(2.0_f64,0.0).sqrt().sqr());
println!("{:?}", twin::Twin::new(twin::Twin::new(2.0_f64,0.0),twin::Twin::default()).sq... | Rust | 0 |
s'].shape[0] == \
dst_bboxes.shape[0] + src_bboxes.shape[0] - 1
assert results['gt_labels'].shape[0] == \
dst_labels.shape[0] + src_labels.shape[0] - 1
assert results['gt_masks'].masks.shape[0] == \
dst_masks.masks.shape[0] + src_masks.masks.shape[0] - 1
assert results['gt_... | Python | 1 |
mut self, _msg: GetDebtsList, _ctx: &mut Context<Self>) -> Self::Result {
let debts: Vec<GetDebtsResult> = self
.debt_data
.iter()
.map(|(key, value)| GetDebtsResult::new(&key, &value))
.collect();
trace!("Debts: {}", debts.len());
Ok(debts)
}
... | Rust | 0 |
macros)]
macro_rules! slog_o(
($($args:tt)*) => {
$crate::OwnedKV(slog_kv!($($args)*))
};
);
/// Macro for building group of key-value pairs in
/// [`BorrowedKV`](struct.BorrowedKV.html)
///
/// In most circumstances using this macro directly is unnecessary and `info!`
/// and other wrappers over `log!... | Rust | 0 |
parametrize("depth", [0.1, 1.0, 10.0])
def test_fingreen3D_roots(omega, depth):
from scipy.optimize import newton, brentq
nk = 100
omega2_over_g = omega**2/9.81
all_roots = cpt.FinGreen3D().fortran_core.green_wave.compute_dispersion_roots(nk, omega2_over_g, depth)
wavenumber = newton(lambda x: omega... | Python | 1 |
# Copyright (c) Yutsuten <https://github.com/Yutsuten>. Licensed under AGPL-3.0.
# See the LICENCE file in the repository root for full licence text.
BEHAVIORS = ['Drain life', 'Do nothing', 'Recover life']
POSITION_OPTIONS = ['Top', 'Bottom']
STYLE_OPTIONS = [
'Default', 'Cde', 'Cleanlooks', 'Fusion', 'Gtk', 'Mac... | Python | 1 |
mul_assign(&ten);
res.add_assign(&Self::from_repr(Self::Repr::from(u64::from(c))).unwrap());
}
None => {
return None;
}
}
}
Some(res)
}
/// Convert this prime field element into a biginteger rep... | Rust | 0 |
# Copyright 2017 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | Python | 1 |
import json
from pathlib import Path
from typer.testing import CliRunner
from MCPStack.cli import StackCLI
from MCPStack.tools.hello_world import Hello_World
runner = CliRunner()
app = StackCLI().app
class TestHello_WorldTool:
def test_actions(self):
tool = Hello_World()
actions = tool.actions(... | Python | 1 |
import torch
from aphrodite.platforms import current_platform
from aphrodite.scalar_type import ScalarType, scalar_types
ALLSPARK_AMPERE_M_CUBLAS_THRESHOLD = 1024
ALLSPARK_SUPPORTED_QUANT_TYPES = [scalar_types.uint8b128]
ALLSPARK_AMPERE_N_ALIGN = 16
ALLSPARK_AMPERE_K_ALIGN = 16
def check_allspark_supported_dtype_sh... | Python | 1 |
###############################################################################
#
# Copyright 2020, University of Stuttgart: Institute for Natural Language Processing (IMS)
#
# This file is part of Adviser.
# Adviser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public ... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.