text string | label_name string | labels int64 |
|---|---|---|
/// Underlying UDP socket, backed by Mio.
socket: net::UdpSocket,
/// The mode in which the socket is in, this determines what methods are
/// available.
mode: PhantomData<M>,
}
impl UdpSocket {
/// Create a UDP socket binding to the `local` address.
///
/// # Notes
///
/// The UDP... | Rust | 0 |
23 => Ok((I::S_SEXT_I32_I16, 4)),
24 => Ok((I::S_BITSET0_B32, 4)),
25 => Ok((I::S_BITSET0_B64, 4)),
26 => Ok((I::S_BITSET1_B32, 4)),
27 => Ok((I::S_BITSET1_B64, 4)),
28 => Ok((I::S_GETPC_B64, 4)),
29 => Ok((I::S_SETPC_B64, 4)),
30 => Ok((I::S_SWAPPC_B64, 4)... | Rust | 0 |
ransient(self.root)
main_frame = ttk.Frame(progreso_window, padding=20)
main_frame.pack(fill='both', expand=True)
# Título
ttk.Label(main_frame,
text=f"📊 PROGRESO DE {usuario_data[1]} {usuario_data[2]}",
font=('Segoe UI', 16, 'bold')).... | Python | 1 |
'title': title,
'text': row['text'],
'author': author,
'score': row['score'],
'pub_date': row['pub_date'],
},
)
self.stdout.write(self.style.SUCCESS('Reviews loaded'))
... | Python | 1 |
[`Thread::unpark`][unpark] from std. A [`Notify`]
/// value contains a single permit. [`notified().await`] waits for the permit to
/// be made available, consumes the permit, and resumes. [`notify_one()`] sets the
/// permit, waking a pending task if there is one.
///
/// If `notify_one()` is called **before** `notif... | Rust | 0 |
ic mut DEVICE_PERIPHERALS: bool = false;
#[doc = r"All the peripherals"]
#[allow(non_snake_case)]
pub struct Peripherals {
#[doc = "PPB"]
pub PPB: PPB,
#[doc = "DLR"]
pub DLR: DLR,
#[doc = "ERU0"]
pub ERU0: ERU0,
#[doc = "ERU1"]
pub ERU1: ERU1,
#[doc = "GPDMA0"]
pub GPDMA0: GPDMA... | Rust | 0 |
Ok(())
}
// waiting for an `event` occurs
// this is, for example, used to wait system call to wait for exiting of child process
pub fn event_wait(&mut self, pid: usize, event: ProcessEvent) -> Result<(), ProcessError> {
let mask = interrupt_disable();
get_process_mut!(self.ptable_lock... | Rust | 0 |
/// * for a literal, its lexical value;
/// * for a blank node, its local identifier;
/// * for a variable, its name.
///
/// # Performance
/// The returned `MownStr` is always borrowed (equivalent to a `&str`),
/// **except** for IRI references where this method *may* allocate a new string
... | Rust | 0 |
jni_bindgen::Local<'env, crate::java::lang::Throwable>> {
// class.path == "android/widget/AbsSpinner", java.flags == PUBLIC, .name == "getAutofillValue", .descriptor == "()Landroid/view/autofill/AutofillValue;"
unsafe {
let __jni_args = [];
let __jni_env = __jni_... | Rust | 0 |
RandomForestClassifier(n_estimators=100, random_state=42)
orig_scores = cross_val_score(clf, X_orig, y_orig, cv=5)
# Train on synthetic, test on original
clf.fit(X_synth, y_synth)
synth_score = clf.score(X_orig, y_orig)
... | Python | 1 |
te_semantic_category_names(
emails, processed_texts, cluster_assignments, tfidf_matrix
)
# Step 6: Group emails by categories
categorized_emails = self._group_emails_by_category(
emails, cluster_assignments, category_names
)
# Step 7: Pos... | Python | 1 |
Vec;
use crate::map::SgMap;
use crate::tree::{
Idx, IntoIter as TreeIntoIter, Iter as TreeIter, IterMut as TreeIterMut, SmallNode,
};
// General Iterators ---------------------------------------------------------------------------------------------------
/// An iterator over the entries of a [`SgMap`][crate::map... | Rust | 0 |
NcTime, fader: NcFadeCb) -> NcResult<()> {
error![unsafe { c_api::ncplane_fadeout(self, time, fader, null_mut()) }]
}
/// Fades out through 'iter' iterations,
/// where 'iter' < 'ncfadectx_iterations(nctx)'.
///
/// *C style function: [ncplane_fadeout_iteration()][c_api::ncplane_fadeout_ite... | Rust | 0 |
}
}
}
#[test]
fn test_intersect_ray_sphere_1() {
//Ray Sphere no intersection, opposing direction
{
let a = Ray::init(&[5f64, 0f64, 0f64], &[-1f64, 0f64, 0f64]);
let b = Sphere::init(&[20f64, 0f64, 0f64], 5f64);
match a.get_intersect(&b) {
(false, None) => (),
... | Rust | 0 |
------")
comp_point += 1
x += 1
elif user_choice == "s":
print("\n-------You won this round-------")
user_point += 1
x += 1
else:
print("\n-------Match draw-------")
match_draw += 1
x += 1
elif comp_rand... | Python | 1 |
# coding=utf-8
import multiprocessing
from pocscan.library.utils import get_poc_files, url_seg
from main.tasks import run_task_in_gevent
from main.models import Tasks_status
from web.lib.crawler import MyCrawler
class Task_control(object):
gevent_num = 100 # 协程数
process_num = 5 # 进程数
... | Python | 1 |
import json
from pathlib import Path
from django.utils.text import slugify
from django.core.management.base import BaseCommand
from library.models.console import Console # Adjust if in a different module
class Command(BaseCommand):
help = "Imports consoles from JSON"
def handle(self, *args, **kwargs):
... | Python | 1 |
import numpy as np
from sklearn.model_selection import train_test_split
class Validate():
def __init__(self, problem):
self.problem = problem
def holdout_validation(self, holdout=0.2, seed=None, rho=None,
rho0_scale=None, how=None, num_iter=1e3,
ve... | Python | 1 |
" {
pub fn load_scene_tab(reg: *mut tm_api_registry_api, load: bool);
}
extern "C" {
pub fn simulate_tab_set_show_playback_controls(tab: *mut tm_tab_o, show: bool);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct tm_task_manager_o {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struc... | Rust | 0 |
import torch
import operator as op
import functools as ft
'''reduce_* helper functions reduce tensors on all dimensions but the first.
They are intended to be used on batched tensors where dim 0 is the batch dim.
'''
def reduce_sum(x, keepdim=True):
# silly PyTorch, when will you get proper reducing sums/means?... | Python | 1 |
let vs = vs.unwrap();
if vs {
write!(stdout, "HWTAGMATCH ").unwrap();
} else {
write!(stdout, "HWTAGMISMATCH ").unwrap();
}
if &tag_out2[0..tv.tag.len()] == tv.tag {
write!(stdout, "TAGMATCH").unwrap();
... | Rust | 0 |
_strides[j], dst)
# ----------------------------------------------------------------------------
# prepare data
data = cgutils.get_null_value(byte_ptr_t)
fnty = llvmlite.ir.FunctionType(llvmlite.ir.VoidType(),
[byte_ptr_ptr_t, intp_ptr_t,
... | Python | 1 |
ilationUnit,
unit_storage_vname: VName,
emitter: EntryEmitter<'a>,
root_dir: &'a PathBuf,
file_vnames: HashMap<String, VName>,
offset_index: OffsetIndex,
}
/// A data structure to analyze and index individual crates
pub struct CrateAnalyzer<'a, 'b> {
emitter: &'b mut EntryEmitter<'a>,
file_... | Rust | 0 |
# Copyright (c) OpenMMLab. All rights reserved.
import mmcv
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmcv.runner import BaseModule
class SELayer(BaseModule):
"""Squeeze-and-Excitation Module.
Args:
channels (int): The input (and output) channels of the SE layer.
ratio (int):... | Python | 1 |
op y),
(Int(x), Int(y)) => Int(x $op y),
(Real(x), Int(y)) => Real(x $op *y as f32),
(Real(x), Real(y)) => Real(x $op y),
(x, y) => return err!(ArgTypeError,
op: Builtin::$sym.sym(),
... | Rust | 0 |
'''
You are a product manager and currently leading a team to develop a new product.
Unfortunately, the latest version of your product fails the quality check.
Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] an... | Python | 1 |
t(test_model)
submodel_accs.append(test_acc)
submodel_losses.append(test_loss)
this_local_accs = []
for i, (worker, size) in enumerate(zip(worker_trainers, client_model_sizes)):
if size == m_siz... | Python | 1 |
Read) -> Result<Model> {
let mut content: String = String::new();
let _ = r.read_to_string(&mut content)?;
parser::parse_model(&content)
}
}
explain_lint! {
///The unary series lint detects trivially-reducible chains of unary operators.
///
///For example, the following chains o... | Rust | 0 |
rue
def allocate_storage(self):
for alloc in self.buffer_allocators:
alloc()
def storage_dtype(self, dtype):
return dtype # overridden by flex gpu transformer
def get_layouts(self, op):
"""
Returns a list of possible axis layouts for the op. The default layout... | Python | 1 |
>(ptr_void: *mut c_void) -> Box<T> {
unsafe { Box::from_raw(ptr_void as *mut T) }
}
/*
* 将Arc转换为*const c_void
*/
#[inline]
pub fn arc2void<T>(ptr_box: Arc<T>) -> *const c_void {
Arc::into_raw(ptr_box) as *const c_void
}
/*
* 将*mut c_void转换为Arc
*/
#[inline]
pub fn void2arc<T>(ptr_void: *mut c_v... | Rust | 0 |
1221318077704626190288641508984014104319842941642570762210967615676477710700081132170451096239\
93976701236193875603478579771137394", res.unwrap()[0].to_dec().unwrap());
}
#[test]
fn _verify_ge_predicate_works() {
let proof = mocks::get_ge_proof();
let c_h = BigNumber::from_dec(... | Rust | 0 |
"""Workflow utility functions for GAIA workflow system."""
from datetime import datetime, timezone
from typing import Any, Dict
from app.config.loggers import general_logger as logger
from app.db.mongodb.collections import workflows_collection
from app.db.utils import serialize_document
async def handle_workflow_er... | Python | 1 |
connection.map_window(icon_window)?.check()?;
let render_op = connection
.get_image(
xproto::ImageFormat::Z_PIXMAP,
icon_window,
0,
... | Rust | 0 |
ator::RightShift => Precedence::Shift,
BinaryExpressionOperator::UnsignedRightShift => Precedence::Shift,
BinaryExpressionOperator::LooseEquals => Precedence::Equality,
BinaryExpressionOperator::LooseNotEquals => Precedence::Equality,
BinaryExpressionOperator::StrictEqual... | Rust | 0 |
il: format!("{:?}", e),
})?;
let underlying = yamls.swap_remove(0);
let value: YamlValue = underlying.try_into()?;
value.try_into()
}
/// ffi_enum! {}
macro_rules! ffi_enum {
(
$( #[$attrs:meta] )*
$v:vis enum $name:ident: $native:ty {
$(
$( #[$variant_att... | Rust | 0 |
NG error: {:?}", err).unwrap(),
}
loop {
match rng.gen_range(20, 200) {
Ok(period) => {
led.toggle().unwrap();
delay.delay(period.ms());
}
Err(err) => hprintln!("RNG error: {:?}", err).unwrap(),
}
}
}
#[exception]
fn HardFa... | Rust | 0 |
Object, PyTryFrom, PyTryInto,
ToPyObject, ToBorrowedObject, IntoPyObject, IntoPyTuple};
pub mod class;
pub use class::*;
/// Procedural macros
pub mod py {
pub use pyo3cls::{proto, class, methods};
#[cfg(Py_3)]
pub use pyo3cls::mod3init as modinit;
#[cfg(not(Py_3))]
pub use p... | Rust | 0 |
# Copyright (C) 2010-2014 GRNET S.A.
#
# 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 program is distributed i... | Python | 1 |
use std::time::Instant;
use tsxlib::timeseries::{TimeSeries};
use tsxlib::data_elements::TimeSeriesDataPoint;
use tsxlib::timeseries_iterators::{FromUncheckedIterator};
use tsxlib::timeutils;
use tsxlib::io::streaming::{TimeSeriesDataPointReceiver};
use std::sync::mpsc;
use std::thread;
... | Rust | 0 |
t mut mem4 = mem[4];
for i in 0..x.len() {
let sum = x[i] + num0 * mem0 + num1 * mem1 + num2 * mem2 + num3 * mem3 + num4 * mem4;
mem4 = mem3;
mem3 = mem2;
mem2 = mem1;
mem1 = mem0;
mem0 = x[i];
y[i] = sum;
}
mem[0] = mem0;
mem[1] = mem1;
mem[... | Rust | 0 |
import subprocess
import os
PYTHON_PATH = "C:/Users/KitsuneX07/AppData/Local/anaconda3/envs/msst/python.exe"
GITHUB_WORKSPACE = "https://github.com/SUC-DriverOld/MSST-WebUI"
command = f"{PYTHON_PATH} -m nuitka --standalone --onefile --follow-imports --output-dir=./build "
command += "--windows-console-mode=disable "
... | Python | 1 |
filename>deploy-chain-0/polkadot/bridges/relays/messages/src/lib.rs<gh_stars>0
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as ... | Rust | 0 |
e, prev[q0], prev[q1]
)
ops_at_updated_moment.append(new_gate.on(q0, q1))
case ops.Pauli() | ops.IdentityGate():
q = op.qubits[0]
ops_at_updated_moment.append(op)
... | Python | 1 |
$X, Y, Z$) is applied to the qubit with probability $p$.
# Similarly, a two-qubit depolarization error applies one of the 15 operators $IX, IY, IZ, XI, XX, ...$ with a given probability.
# %%
@squin.kernel
def noisy_linear_ghz(n: int, p_single: float, p_paired: float):
q = squin.qubit.new(n)
# define the no... | Python | 1 |
stando otimização com restrições...")
analisador.otimizacao_com_restricoes_tempo(tempo_max_expresso=25, tempo_max_prioritario=40)
print("\n4. Comparando cenários...")
analisador.comparar_cenarios()
print("\n5. Gerando relatório completo...")
analisador.gerar_relatorio_completo("analise_com... | Python | 1 |
import pytest
from flask import url_for
from tests import create_admin_authorization_header
@pytest.mark.usefixtures("_notify_db")
class TestUserIdFilter:
def test_no_user_id_attribute_outside_request(self, caplog, notify_api):
caplog.set_level("INFO")
notify_api.logger.info("blah")
asse... | Python | 1 |
# -*- coding: utf-8 -*-
"""
InputSequence.py(InputSequenceCommand)
http://cosing-plus.com/
This plug-in will output a sequence numbers in
mulutiple caret position.
ver 2.0.1 - 2015.9.8
"""
import sublime, sublime_plugin
import re,string
class InputSequenceCommand(sublime_plugin.TextCommand):
#... | Python | 1 |
t\xc5\xaf\xf5&\x9a\x86\xa7\xa9S\x154\xf7\xda.L0=\x8a1\x8ar\x1c<\x0c\x95\x95h\tS/\xcf\x0e$I\xa6\xb5%\xb1j\xed\xf5\xaa\r\xe6W\xbac{9";
// // 0x9313225df88406e555909c5aff5269aa6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b525416aedbf5a0de6a57a637b39b
// let iv = b"\x93\x13\x22]\xf8\x84\x06\xe5U\x90\x9c... | Rust | 0 |
problem_name: "Test 3".to_string(),
overall_oks: 3,
},
Task {
id: "4".to_string(),
language: Language::Ada,
problem_name: "Test 4".to_string(),
... | Rust | 0 |
ults to 256.
n_steps (int, optional): Number of steps along each axis of latent representation to generate grid of indicatrices. Defaults to 20.
n_polygon (int, optional): Number of points in each polygon approximating the unit sphere in pullback metric. Defaults to 50.
Returns
-------
... | Python | 1 |
from solution import *
``
import pytest
def test_square_root_approximate_positive():
a = 16
root, iterations, converged = square_root_approximate(a)
assert abs(root - 4.0) < 1e-14
assert iterations <= 9999
assert converged
def test_square_root_approximate_zero():
a = 0
root, iterations, c... | Python | 1 |
nterval_log::IntervalLogWriterBuilder::new()
.begin_log_with(&mut log, &mut serializer)
.unwrap();
let dur = time::Duration::new(5, 678_000_000);
for h in histograms.iter() {
writer
.write_histogram(h, time::Duration::new(1, 234_000_000), dur, None)
... | Rust | 0 |
struct Example; // Most of the types can be an actor.
//!
//! // While `Actor` implementation can be customized, it is not required.
//! #[async_trait]
//! impl Actor for Example {}
//!
//! // Message handler that calculated sum of two numbers.
//! #[async_trait]
//! impl Handler<(u8, u8)> for Example {
//! type R... | Rust | 0 |
ergens: allergens.trim().split(", ").collect(),
}
}
fn ingredients(&self) -> &[&'a str] {
&self.ingredients
}
fn allergens(&self) -> &[&'a str] {
&self.allergens
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn part1_example() {
assert_eq!(
... | Rust | 0 |
) < 1e-15);
assert!(dist((0.0, 0.0), proj(4.0 * HALF_PI, 0.0)) < 1e-15);
assert!(dist((0.0, -1.0), proj(0.0 * HALF_PI, -TRANSITION_LATITUDE)) < 1e-15);
assert!(dist((1.0, -2.0), proj(0.0 * HALF_PI + PI_OVER_FOUR, -HALF_PI)) < 1e-15);
assert!(dist((2.0, -1.0), proj(1.0 * HALF_PI, -TRANSITION_LATITUDE)) <... | Rust | 0 |
import matplotlib.pyplot as pl
from sklearn import metrics
import numpy as np
# 相关库
def plot_matrix(y_true, y_pred, labels_name, title=None, thresh=0.8, axis_labels=None,lr=None,save=False,savepath=None):
# 利用sklearn中的函数生成混淆矩阵并归一化
cm = metrics.confusion_matrix(y_true, y_pred, labels=labels_name, sample_weight=None... | Python | 1 |
from SimpleSDK import RUIWOTools
import yaml
import os
import signal
import pwd
import time
ruiwo = RUIWOTools()
def get_dev_id(config):
DEV_ID1 = config['address']['Left_joint_arm_1']
DEV_ID2 = config['address']['Left_joint_arm_2']
DEV_ID3 = config['address']['Left_joint_arm_3']
DEV_ID4 = config['addre... | Python | 1 |
[(x + w/2, y + h/2, (x,y,w,h))
for x,y,w,h in cells]
cells_sorted_by_y = sorted(cells_with_centers, key=lambda x: x[1])
rows = [cells_sorted_by_y[i:i+7] for i in range(0, CELL_COUNT, 7)]
return [cell[2] for row in rows for cell in sorted(row, key=lambda x: x[0])]
def detect_cells... | Python | 1 |
ype"])
atom37_mask = get_atom37_mask(data["aatype"])
protein = Protein(np.array(atom37), np.array(data["aatype"]),
np.array(atom37_mask), np.array(data["residue_index"]),
np.array(base_cha... | Python | 1 |
import logging
from botocore.exceptions import ClientError, NoCredentialsError, PartialCredentialsError
from fastapi import HTTPException, Response
from .base import AWS
logger = logging.getLogger(__name__)
class S3(AWS):
def __init__(self,
aws_access_key_id: str=None,
aws_secr... | Python | 1 |
ts.maximum_number_of_gas_units.get(),
txn_data.max_gas_amount().get()
);
return Err(VMStatus::Error(
StatusCode::MAX_GAS_UNITS_EXCEEDS_MAX_GAS_UNITS_BOUND,
));
}
// The submitted transactions max gas units needs to be at least enough t... | Rust | 0 |
role: RoleType, account: AccountId) {
self.get_mut().members.take(&(role, account));
self._emit_role_revoked(role, account, Self::env().caller());
}
default fn _set_role_admin(&mut self, role: RoleType, new_admin: RoleType) {
let entry = self.get_mut().admin_roles.entry(role).or_insert... | Rust | 0 |
d lengthen this time. This corresponds to the parameter tLOW in the I2C bus specification. I2C bus specification parameters tBUF and t SU;STA have the same values and are also controlled by MSTSCLLOW."]
#[inline]
pub fn mstscllow(&mut self) -> _MSTSCLLOWW {
_MSTSCLLOWW { w: self }
}
#[doc = "Bit... | Rust | 0 |
Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, scale_info::TypeInfo)]
pub struct BestPathChangesPayload<Public, BlockNumber, C: Currency, A: Amount> {
changes: Vec<(C, C, Option<PricePath<C, A>>)>,
nonce: u64,
block_number: BlockNumber,
public: Public,
}
impl<T: SigningTypes, C: Currency, A: Amount> SignedPay... | Rust | 0 |
("[AmapManager] 注册IP定位工具成功")
def _register_weather_tool(self, add_tool, PropertyList, Property, PropertyType):
"""
注册天气查询工具.
"""
props = PropertyList(
[
Property(
"city",
PropertyType.STRING,
),
... | Python | 1 |
"""
流管理器模組
此模組實現了流管理器,用於管理數據流的生產者、消費者和處理器。
"""
import json
import logging
import os
import queue
import threading
import time
from typing import Any, Dict, List, Optional
from .consumer import Consumer
from .message import Message, MessageType
from .pipeline import Pipeline
from .processor import Processor
from .pro... | Python | 1 |
pub ptr_records: Vec<PtrRecord>,
#[doc = "The list of SRV records in the record set."]
#[serde(rename = "SRVRecords", default, skip_serializing_if = "Vec::is_empty")]
pub srv_records: Vec<SrvRecord>,
#[doc = "The list of TXT records in the record set."]
#[serde(rename = "TXTRecords", default, skip_s... | Rust | 0 |
(
GL::ELEMENT_ARRAY_BUFFER, Some(&index_data), indices.get_buffer_usage()
);
Ok(())
}
}
// Copyright © 2015-2017 winapi-rs developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or... | Rust | 0 |
)
assert (
len(self._env_observations[i])
<= self.config.TASK_CONFIG.ENVIRONMENT.MAX_EPISODE_STEPS
), "Trajectories should be no more than the maximum episode steps."
# out = self._preload[self.rank]
# self._preload = self._preload... | Python | 1 |
::open(main_asm){ // if file does not exist
if let Err(why) = File::create(main_asm){ // create new file
panic!("Could not write to {}, try changing to the root(the name) directory of the project: {}", main_asm, why.description())
}
}
};
match File::open("./.asmc"... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
完整改造总结演示 - Complete Refactor Summary Demo
🔥 展示借鉴 LangChain @tool 装饰器思想的完整改造成果
三步改造完成:
✅ 第一步:创建 @tool 装饰器系统
✅ 第二步:重构现有工具为函数式
✅ 第三步:清理冗余的手动注册逻辑
"""
import logging
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def demonstrate_c... | Python | 1 |
ROTOCOLS);
#[derive(Debug, Serialize, Deserialize)]
pub struct CrtcInfo {
pub x: i16,
pub y: i16,
pub width: u16,
pub height: u16,
}
impl From<randr::GetCrtcInfoReply> for CrtcInfo {
fn from(reply: randr::GetCrtcInfoReply) -> Self {
let (width, height) = match reply.rotation() {
... | Rust | 0 |
from fastapi import FastAPI
from prometheus_fastapi_instrumentator import Instrumentator
from starlette.middleware.sessions import SessionMiddleware
from routers.customer_manager import slots, customers, visits, workday
from routers.employees_manager import employees
from routers.users_manager import organization, use... | Python | 1 |
PlainTextEdit.tabStopWidth = (
lambda self, *args, **kwargs: self.tabStopDistance(*args, **kwargs)
)
QLineEdit.getTextMargins = lambda self: (
self.textMargins().left(),
self.textMargins().top(),
self.textMargins().right(),
self.textMargins().bottom(),
)
# Map De... | Python | 1 |
recv(self.receiver, task) => match task {
Some(t) => Ok(t),
None => Err(RecvTimeoutError::Disconnected),
}
recv(crossbeam_channel::after(timeout)) => Err(RecvTimeoutError::Timeout),
}
}
}
impl<T> Drop for Receiver<T> {
#[inline]
fn drop(&mut s... | Rust | 0 |
import argparse, json, numpy as np, pandas as pd
from pathlib import Path
from sklearn.metrics import accuracy_score, f1_score
from sklearn.svm import SVC
from xgboost import XGBClassifier
GLOBAL_CLASSES = np.array([0,1,2]) # 0=Nov,1=Int,2=Exp
def evaluate(y_true, y_pred):
return dict(acc=float(accuracy_score(y... | Python | 1 |
# Copyright Allo authors. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import os
import pytest
import allo
from allo.library.systolic import systolic
from allo.ir.types import int8
import numpy as np
import allo.backend.hls as hls
device = "cpu"
N, L, D = 1, 4, 4
def test_int8_linear():
try:
... | Python | 1 |
import json
import os
from collections import defaultdict
import numpy as np
import sys
import glob
if __name__ == '__main__':
base_dir = sys.argv[1]
print(base_dir)
patterns = ['*', '*/*', '*/*/*']
f_list = sum([list(glob.glob(os.path.join(base_dir, p))) for p in patterns], [])
review_files = [... | Python | 1 |
::new_message("A message with no input").run() {
Err(Error::Blank) => (), // ok
_ => assert!(false),
}
}
}
<reponame>DutchGhost/tablepower
extern crate proc_macro;
extern crate syn;
#[macro_use]
extern crate quote;
use self::proc_macro::TokenStream;
use self::syn::{
parse::{P... | Rust | 0 |
_option("-p", "--pid-file",
help="specify a pid file")
(opts, args) = parser.parse_args()
if opts.config:
load_conf(opts.config)
conf = get_conf()
logging.getLogger().setLevel(logging.DEBUG)
pid_file = opts.pid_file
if pid_file is None:
pid_file = conf.get... | Python | 1 |
.borrow_multiplier.into(),
)
.unwrap();
let oracle_cache = get_oracle(cache, &info.oracle_symbol).unwrap();
let price: I80F48 = oracle_cache.price.into();
// Price is only weighted when collateral is non-negative.
let weighted_price = match is_weighted && v >= 0u64 {
... | Rust | 0 |
ict]): List of card data from the API
rarity (str): The rarity to filter by
Returns:
List[Dict]: Filtered list of cards with the specified rarity
"""
filtered_cards = []
for card in cards:
if card.get("rarity", "").lower() == rarity.lower():
filtered_cards.ap... | Python | 1 |
# NOQA F401
from .navigationrail import (
MDNavigationRail,
MDNavigationRailFabButton,
MDNavigationRailItem,
MDNavigationRailMenuButton,
)
| Python | 1 |
xb2Ip\xedn`quo;\xda\xad\xdc~|\x0c\
\x89\x0b\xc3\xb4z\xa9\xfbHBNWm%v\xd5\xf5\
I5\xd3\xfe\x0e\xbb\x9c\x0f\x13>e\x14\xdc\x92\xd3]\
\x17E\xba\xbe\xb6o\xa6\xf7\xec&\xa9\xf1\x93E\xd2\x9e\
\x1b\x0b\xeb\xbd8\xde\x9f\xed[X,\xe7\xd4m\xf4\xf9\
/g\xd3\xed\x22\x8bR\xd3,\xa7\xd3-\xe7\xbdm\xb2\
K\xe5\xa5\xecp]\xff\x00\xc4\xc63\x0bFE\... | Python | 1 |
onfig.jobsrv[0].log_port, 9021);
assert_eq!(&format!("{}", config.jobsrv[1].host), "2.2.2.2");
assert_eq!(config.jobsrv[1].port, 9000);
assert_eq!(config.jobsrv[1].heartbeat, 5567);
assert_eq!(&config.features_enabled, "FOO,BAR");
assert_eq!(config.target,
Pack... | Rust | 0 |
"Player {}({}) has joined channel {}!",
player_name, player_id, self.name
);
return true;
}
#[inline(always)]
/// Remove a player from this channel
///
/// If it's a permanent channel, should pass Some(player_sessions),
/// it means channel info will broadcast to ... | Rust | 0 |
,
CLIENT_ADDR,
&MinerAddresses::default(),
start_epoch,
end_epoch + 1,
);
let d2 = get_deal_proposal(&mut rt, deal_id2);
let input = SectorDataSpec {
deal_ids: vec![deal_id1, deal_id2],
sector_type: RegisteredSealProof::Sta... | Rust | 0 |
async def app(scope, receive, send):
assert scope['type'] == 'http'
await send({
'type': 'http.response.start',
'status': 200,
'headers': [
[b'content-type', b'text/plain'],
],
})
await send({
'type': 'http.response.body',
'body': b'Hello, wor... | Python | 1 |
.serialized_length());
assert!(expected_large_cost > expected_small_cost);
let large_write_cost = Ratio::new(large_add_function_cost.value(), cost_per_byte);
assert_eq!(
large_write_cost.fract().to_integer(),
U512::zero(),
"cost does not divide without remainder"
);
assert... | Rust | 0 |
er to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_to_address(&mut self) -> &mut ::std::vec::Vec<u8> {
if self.to_address.is_none() {
self.to_address.set_default();
}
self.to_address.as_mut().unwrap()
}
// Take fie... | Rust | 0 |
from dolfin import *
from multiphenics import *
###########
# Helper function to generate subdomain restriction based on a gmsh subdomain id
def generate_subdomain_restriction(mesh, subdomains, subdomain_id):
D = mesh.topology().dim()
# Initialize empty restriction
restriction = MeshRestriction(mesh, None)... | Python | 1 |
0, 30.0, 40.0);
/// let matrix2: [f64; 4] = create(10.0, 20.0, 30.0, 40.0);
/// let mut init_matrix = Matrix2::new(matrix1);
/// let matrix = init_matrix.add(matrix2);
/// assert_eq!(matrix.len(), 4);
/// let test_matrix: [f64; 4] = [20.0, 40.0, 60.0, 80.0];
/// assert_eq!(equal(matrix, test_matrix), true);... | Rust | 0 |
Values [2, 4, 6, 8] doesn't exist and doesn't cause collision, so bloom.contains should return false
for num in [2_u8, 4, 6, 8] {
let single_value_bloom =
create_bloom(u8::to_data_type(), Series::from_data(vec![num]), &bloom)?;
assert!(!bloom.contains(&single_value_bloom), "{}", num);
... | Rust | 0 |
= catch_unwind(AssertUnwindSafe(|| {
unsafe {
buckets.try_extend(collection, Size(0), capacity, &hooks);
}
}));
assert!(panicked.is_err());
assert!(buckets.0[0].is_allocated());
assert!(buckets.0[1].is_allocated());
assert!(!buckets.0[2].is_allocated());
}
#[test]
fn b... | Rust | 0 |
#[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 &= !(1 << 28);
self.w.bits |= ((value as u32) & 1) << 28;
self.w
}
}
#[doc... | Rust | 0 |
: {
"model_name": "voyage-lite-01"},
(("name", "voyage-lite-01-instruct"), ("kind", "CHAT"), ("api_id", 35)): {
"model_name": "voyage-lite-01-instruct"},
# xAI
(("name", "Grok 3"), ("kind", "CHAT"), ("api_id", 40)): {
"model_name": "gr... | Python | 1 |
te:
if not os.path.isdir(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
with open(filename + ".saved", "w", encoding="utf-8") as saved:
with open(filename, "w", encoding="utf-8") as memory:
target = saved
... | Python | 1 |
ch is considerably
/// quicker than the standard method.
///
/// However, this requires additional private fields in the schema to
/// be affective with relevancy as names often get corrected to dictionary
/// words which alters the behaviour of the ranking.
/// To counter act this, the system runs the same correction ... | Rust | 0 |
"""Вспомогательные функции для работы с данными эл.почты"""
from datetime import datetime
from email.header import decode_header
from email.utils import parsedate_tz, mktime_tz
import pytz
def parse_date(date_str):
"""Преобразование даты из строки в datetime."""
parsed_date = parsedate_tz(date_str)
if p... | Python | 1 |
header. E.g., a pointer of 40 (the length of a single IPv6
// header) would indicate that the Next Header field from that
// header - and hence of the first encapsulated packet - was
// unrecognized.
//
// NOTE: Since header_len is a usize, this could theoretically
// be... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.