text string | label_name string | labels int64 |
|---|---|---|
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import pytest
import torch
from pyro.distributions import MultivariateNormal
from tests.common import assert_equal
def random_mvn(loc_shape, cov_shape, dim):
"""
Generate a random MultivariateNormal distribution for test... | Python | 1 |
420, 430, 440, 450];
/// List of supported es glsl versions
pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320];
pub type BindingMap = std::collections::BTreeMap<crate::ResourceBinding, u8>;
impl crate::AtomicFunction {
fn to_glsl(self) -> &'static str {
match self {
Self::Add | Self::... | Rust | 0 |
11)
} else if len % 13 == 0 {
Self::is_supported_fft_len(is_complex, len / 13)
} else {
false
}
}
fn fft(is_complex: bool, source: &[T], target: &mut [T], reverse: bool) {
if !is_complex {
panic!("Real fft isn't supported, call `has_gpu_suppo... | Rust | 0 |
AllocationScope = ::std::os::raw::c_uint;
pub const VK_INTERNAL_ALLOCATION_TYPE_EXECUTABLE: VkInternalAllocationType = 0;
pub const VK_INTERNAL_ALLOCATION_TYPE_MAX_ENUM: VkInternalAllocationType = 2147483647;
pub type VkInternalAllocationType = ::std::os::raw::c_uint;
pub const VK_FORMAT_UNDEFINED: VkFormat = 0;
pub co... | Rust | 0 |
# Gracin Goff
# UWYO COSC 1010
# 10-15-2024
# HW 01
# Lab Section: 10
# Sources, people worked with, help given to:
# your
# comments
# here
# Homework Question:
#
# You are given a list of dictionaries where each dictionary represents a student and their scores
# in different subjects.
#
# Student Data:
students = [
... | Python | 1 |
use std::process::Command;
// just for testing to see if it's working
fn make_exe() {
Command::new("rm")
.args(&["-rf", "test"])
.output()
.expect("failed to execute process");
Command::new("gcc")
.args(&["out/test.ll", "-o", "out/test"])
.output()
.expect("failed to execute process");
}
... | Rust | 0 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: networks_sm_devices_refresh_details
short_description: Resource module for networks _sm _devices _refreshdetails
d... | Python | 1 |
{
fn route(&self, data: &D) -> FnResult<u64> {
(self.func)(data)
}
}
#[macro_export]
macro_rules! route {
($func: expr) => {
RouteClosure::new($func)
};
}
#[macro_export]
macro_rules! box_route {
($func: expr) => {
B... | Rust | 0 |
>,
/// Code represents the error status code (404, 403, 401, ...).
#[serde(rename = "status_code", skip_serializing_if = "Option::is_none")]
pub status_code: Option<i64>,
}
impl JsonError {
/// Error responses are sent when an error (e.g. unauthorized, bad request, ...) occurred.
pub fn new() -> Js... | Rust | 0 |
"SignedAmount addition error")
}
}
impl ops::AddAssign for SignedAmount {
fn add_assign(&mut self, other: SignedAmount) {
*self = *self + other
}
}
impl ops::Sub for SignedAmount {
type Output = SignedAmount;
fn sub(self, rhs: SignedAmount) -> Self::Output {
self.checked_sub(rhs).... | Rust | 0 |
) = channel();
self.handle_ws_connect(in_receiver, out_sender);
// write task
Thread::spawn(move || {
// ugh: https://github.com/mozilla/rust/blob/3dbc1c34e694f38daeef741cfffc558606443c15/src/test/run-pass/kindck-implicit-close-over-mut-var.rs#L40-L44
// work to fix thi... | Rust | 0 |
:
sample_rays = gen_rays_from_single_image(
img_wh[1], img_wh[0],
sample['query_image'],
sample['query_intrinsic'],
sample['query_c2w'],
depth=sample['query_depth'],
mask=sample['query_mask'] if self.clean_image ... | Python | 1 |
import base64
import hashlib
import os
def generate_pkce_pair():
verif = base64.urlsafe_b64encode(os.urandom(64)).decode('utf-8').rstrip('=')
chall = base64.urlsafe_b64encode(
hashlib.sha256(verif.encode('utf-8')).digest()
).decode('utf-8').rstrip('=')
return verif, chall
| Python | 1 |
@contextmanager
def torch_distributed_zero_first(local_rank: int):
if local_rank not in [-1, 0]:
dist.barrier()
yield
if local_rank == 0:
dist.barrier()
| Python | 1 |
)
}
// WF if inner type is `Sized`.
ty::Slice(..) => wf_clause_for_slice(self.infcx.tcx),
// WF if inner type is `Sized`.
ty::Array(_, length) => wf_clause_for_array(self.infcx.tcx, length),
... | Rust | 0 |
bounding_box::*;
use super::framebuffer::*;
use super::geometry::*;
use super::geometry::{Line, Rect};
pub struct ProgressBar {
bbox: BBox,
progress: u8,
color: Color,
}
pub struct Scroller {
bbox: BBox,
position: i32,
width: i32,
orient: Orientation,
color: Color,
}
pub struct Table ... | Rust | 0 |
_req,
} = self;
f.debug_struct("UnreadyService")
.field("key", key)
.field("cancel", cancel)
.field("service", service)
.finish()
}
}
<filename>src/test/ui/const-generics/const-types.rs
// run-pass
#![feature(const_generics)]
//~^ WARN the feature `co... | Rust | 0 |
#!/usr/bin/env python
import json
import os
import sys
import argparse
from pprint import pprint
from typing import List, Optional, Tuple
from cluster import filter_packages, filter_imports
def eval_pkglists(filtered_imports: List[List[str]], pkglists: List[List[str]]) -> None:
def _select_pkglist(file_imports: L... | Python | 1 |
# Generated by Django 3.2.25 on 2024-11-20 21:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('issues', '0102_alter_issue_priority'),
]
operations = [
migrations.AlterField(
model_name='issue',
name='priority',... | Python | 1 |
.bitext, side='target')
else:
e = cdec.sa.DataArray(from_text=args.target)
e.write_binary(e_bin)
stop_time = monitor_cpu()
logger.info('Compiling target data array took %f seconds', stop_time - start_time)
start_time = monitor_cpu()
logger.info('Precomputing frequent phrases')
preco... | Python | 1 |
self._combined_update_talent_request_body.basic_info = basic_info
return self
def education_list(self,
education_list: List[TalentCombinedEducationInfo]) -> "CombinedUpdateTalentRequestBodyBuilder":
self._combined_update_talent_request_body.education_list = education_lis... | Python | 1 |
while index < length {
num_memory_letters += 1;
if letters[index] == '\\' {
if letters[index + 1] == 'x' {
index += 4;
} else {
index += 2;
}
} else {
index += 1;
... | Rust | 0 |
result = format!("{:?}", tgram);
assert_eq!("Telegram { header: Header { timestamp: 2017-01-29T11:22:13Z, channel: 0x11, destination_address: 0x1213, source_address: 0x1415, protocol_version: 0x36 }, command: 0x17, frame_data: ... }", result);
}
}
<gh_stars>0
extern crate serde;
pub mod main;
#[cfg(test... | Rust | 0 |
}
}
fn call_function(this: &Expression, block: &Block) -> quest_core::Result<Object> {
use crate::block::LineResult;
let this = this.execute()?;
let call_op =
match block.paren_type() {
ParenType::Square => "[]",
_ => "()",
};
match block.run_block()? {
Some(LineResult::Single(s)) => this.call_attr_... | Rust | 0 |
IoErrorRepr::Os(code) => unsafe {
mem::transmute(io::Error::from_raw_os_error(code).description())
},
IoErrorRepr::Kind(kind) => unsafe {
mem::transmute(io::Error::from(kind).description())
},
IoErrorRepr::Custom(_, ref inner) ... | Rust | 0 |
newtError>;
/// Error codes for Mynewt API
#[repr(i32)]
#[derive(PartialEq)]
#[allow(non_camel_case_types)] // Allow type names to have non-camel case
pub enum MynewtError {
/// Error code 0 means no error.
SYS_EOK = os::SYS_EOK as i32,
SYS_ENOMEM = os::SYS_... | Rust | 0 |
s/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ch7_out](ch7_out) module"]
pub type CH7_OUT = crate::Reg<u16, _CH7_OUT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CH7_OUT;
#[doc = "`read()` method returns [ch7_out::R](ch7_out::R) reader structure"]
impl crate::Readable for C... | Rust | 0 |
=> <$a, $b, $c, $d, $e, $f, $g, $h>; Fed5<$a, $c, $e, $f, $h> => Fed8<$a, $b, $c, $d, $e, $f, $g, $h>; Fed5::T1, Fed5::T2, Fed5::T3, Fed5::T4, Fed5::T5);
fed_promotion!(Fed5 => Fed8; <$a, $c, $e, $g, $h> => <$a, $b, $c, $d, $e, $f, $g, $h>; Fed5<$a, $c, $e, $g, $h> => Fed8<$a, $b, $c, $d, $e, $f, $g, $h>; Fed5... | Rust | 0 |
ivity_penalty(
state: &BeaconState,
index: usize,
epochs_since_finality: u64,
previous_total_balance: u64,
spec: &ChainSpec,
) -> Result<u64, BeaconStateError> {
Ok(get_base_reward(state, index, previous_total_balance, spec)?
+ state.get_effective_balance(index, spec)? * epochs_since_fin... | Rust | 0 |
es
///
/// ```
/// use no_std_net::{IpAddr, Ipv4Addr, Ipv6Addr};
///
/// fn main() {
/// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv4(), true);
/// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv4(),
/// false);
/// ... | Rust | 0 |
ty_count': len(self.activity_deque),
'transition_count': len(self.transition_history),
'gc_count': gc.get_count()
}
except Exception as e:
logger.error(f"❌ Memory usage check failed: {e}")
return {}
def get_performance_sta... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
def analytical_solution(t, T0, m):
"""Аналитическое решение dT/dt = -mT"""
return T0 * np.exp(-m * t)
def f(t, T, m):
"""Правая часть ОДУ dT/dt = -mT"""
return -m * T
def adams_pc2(f, t0, y0, h, n, m):
"""Многошаговый метод Адамса 2-го порядка (П... | Python | 1 |
ns a new
/// thread, and executes the loop on that thread. Only loops started using `spawn` can be
/// cancelled.
///
/// For example, the implementation below shows how a classic server accept loop could be turned
/// into a cancellable accept loop. If [`Handle::cancel`] is called, then at most one more
/// connection... | Rust | 0 |
false];
let rmm_bigger: RangeMinMaxTree = RangeMinMaxTree::new(parenthesis_bigger,16);
assert_eq!(rmm_bigger.fwdsearch(11,1), 18);
assert_eq!(rmm_bigger.fwdsearch(6,0), 18);
}
#[test]
fn test_fwdsearch2(){
let parenthesis: BitVec<u8> = bit_vec![true, true, true, false, tr... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Author: jian wei
File Name: video_service.py
"""
from typing import Optional, Dict, Any, List
from jianyingdraft.jianying.video import VideoSegment
from jianyingdraft.utils.response import ToolResponse
def add_video_segment_service(
draft_id: str,
material: str,
target_timerang... | Python | 1 |
import MySQLdb
import fileinput
import re
config_file = "/etc/ossim/framework/ossim.conf"
def readDbInfo():
user = ''
password = ''
for line in fileinput.input(config_file):
p = re.compile(r"ossim_pass=(?P<pass>\S+)")
m = p.match(line)
if (m):
password = m.group(1)
... | Python | 1 |
mock_client.post(f"/learning/{key}/learning-path")
for key in resume_keys
]
responses = await asyncio.gather(*tasks)
# Then: 모든 요청이 성공적으로 처리된다
assert len(responses) == 3
assert all(response.status_code == 200 for response in responses)
#... | Python | 1 |
self._ctx, value
)
# Python 3.13+ makes get_unverified_chain() a public API that only returns DER
# encoded certificates. We detect whether we need to call public_bytes() for 3.10->3.12
# Pre-3.13 returned None instead of an empty list from get_unverified_chain()
if sys.version_info >= (3, 13):
... | Python | 1 |
import unittest
from fastapi.testclient import TestClient
from unittest.mock import patch, MagicMock
from api import app, get_db, HTTPException
class TestFastAPI(unittest.TestCase):
def setUp(self):
self.client = TestClient(app)
@patch('api.SessionLocal')
def test_get_data_success(self, mock_Sess... | Python | 1 |
alized.")
# configure learning rate
bs, base_lr = config.data.params.batch_size, config.model.base_learning_rate
if not cpu:
ngpu = len(lightning_config.trainer.gpus.strip(",").split(','))
else:
ngpu = 1
if 'accumulate_grad_batches' in lightning_config... | Python | 1 |
# -*- coding: utf-8 -*-
from base64 import urlsafe_b64encode
from ..auth import digest
from .. import conf
class Client(object):
conn = None
def __init__(self, mac=None):
if mac is None:
mac = digest.Mac()
self.conn = digest.Client(host=conf.RS_HOST, mac=mac)
def stat(self, bucket, key):
return self.conn... | Python | 1 |
ediction, task):
# Obtain ground truth for the query
gt = pd.read_csv(ground_truth_file)
ground_truth = gt['num_points'].tolist()
# Compare the results
tp1 = prediction[prediction['num_points'].isin(ground_truth)].shape[0]
fp1 = prediction[~prediction['num_points'].isin(ground_truth)].shape[0]
... | Python | 1 |
group, $size, $closure)
};
}
#[macro_export]
macro_rules! bench_nalgebra_f32x4 {
($group:ident, $closure:expr) => {
bench_lib!("nalgebra_f32x4", $group, $closure)
};
($group:ident, $size:expr, $closure:expr) => {
bench_lib!("nalgebra_f32x4", $group, $size, $closure)
};
}
#[macro_ex... | Rust | 0 |
def __init__(self, name):
super().__init__(name)
self._registry_dict_block_name = {}
| Python | 1 |
ethod
def tensorize(mol_batch):
padding = torch.zeros(ATOM_FDIM + BOND_FDIM)
fatoms, fbonds = [], [padding] # Ensure bond is 1-indexed
in_bonds, all_bonds = [], [(-1, -1)] # Ensure bond is 1-indexed
scope = []
total_atoms = 0
for smiles in mol_batch:
mo... | Python | 1 |
Buffer as GlCommandBuffer,
},
};
// type aliases
type Rgba8Target = gfx::handle::RenderTargetView<R, Rgba8>;
type GlEncoder = gfx::Encoder<R, GlCommandBuffer>;
type PipelineState = gfx::PipelineState<R, context::pipe::Meta>;
type ShaderResourceView = gfx::handle::ShaderResourceView<R, [f32; 4]>;
type TextureHandl... | Rust | 0 |
ndall("(\S+:\S+@\S+:\d+)", res.text)
if len(ips) < 1:
logger.error(f"API代理提取失败,请求响应: {res.text}")
raise Exception("代理提取失败")
else:
[_proxies.append(ip) for ip in ips]
break
... | Python | 1 |
selection in selections:
thread_id = selection['thread_id']
session_id = selection['session_id']
document_names = selection.get('document_names', [])
for doc_name in document_names:
try:
# Expor... | Python | 1 |
request, rng),
"Redeem" => self.process_redeem(&request, &request_wrapper.host, &request_wrapper.http),
x => return Err(format!("unknown request: {}", x).into())
}
}
fn process_issue<R: Rng>(&self, request: &types::ClientRequest, rng: &mut R) -> Result<String, Box<Error>> {
... | Rust | 0 |
# Software License Agreement (BSD License)
#
# Copyright (c) 2013, Eric Perko
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyrigh... | Python | 1 |
eranker and self.reranker_service and messages:
try:
rerank_count = min(len(messages), query.limit * 2)
rerank_messages = messages[:rerank_count]
reranked_messages = await self.reranker_service.rerank_results(
query=query.t... | Python | 1 |
w_context, frame),
Tile::Railgun => railgun(view_context, frame),
Tile::Rifle => rifle(view_context, frame),
Tile::GausCannon => gaus_cannon(view_context, frame),
Tile::Oxidiser => oxidiser(view_context, frame),
Tile::LifeStealer => life_stealer(view_context, frame),
Tile... | Rust | 0 |
Literal::int(i)) }
pub fn ip_addr( i:std::net::IpAddr) -> Self {
Self::FlatLiteral(FlatLiteral::ip_addr(i))
}
pub fn label( l:labels::Label) -> Self {
Self::FlatLiteral(FlatLiteral::label(l))
}
pub fn regex( pr:parser::PolicyRegex) -> Self {
Self::FlatLiteral(FlatLiteral::reg... | Rust | 0 |
activity));
}
}
fn on_event(&self, event: &Event, _ctx: Context<S>) {
let metadata = event.metadata();
let level = match *metadata.level() {
Level::TRACE => os_log_type_t_OS_LOG_TYPE_DEBUG,
Level::DEBUG => os_log_type_t_OS_LOG_TYPE_DEBUG,
Level::INFO => os_log_type_t_OS_LOG_TYPE_INFO,
Level::WARN =... | Rust | 0 |
&KC::EItem,
) -> Result<Option<(KC::DItem, DC::DItem)>>
where
KC: BytesEncode + BytesDecode<'txn>,
DC: BytesDecode<'txn>,
{
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let mut cursor = RoCursor::new(txn, self.dbi)?;
let key_bytes: Cow<[u8]> = KC::byt... | Rust | 0 |
import numpy as np
import math
import matplotlib.pyplot as plt
def bias_variance_dartboard():
# Dartboard example
N_DARTS = 20
LABEL_SIZE = 14
fig, axes = plt.subplots(2, 2, subplot_kw=dict(polar=True))
fig.set_size_inches((8, 8))
theta = np.linspace(0, 2*math.pi, 1000)
data = np.array([... | Python | 1 |
|m: &StorageReadRequest| { &m.transaction_id },
|m: &mut StorageReadRequest| { &mut m.transaction_id },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
"datu... | Rust | 0 |
BlobcacheMetrics>,
backend: Arc<dyn BlobBackend + Sync + Send>,
}
impl BlobCacheState {
fn get(&self, blob: &RafsBlobEntry) -> Option<(RawFd, u64, Arc<dyn ChunkMap + Sync + Send>)> {
self.blob_map
.get(&blob.blob_index)
.map(|(file, size, chunk_map)| (file.as_raw_fd(), *size, ch... | Rust | 0 |
heuristics
#[derive(Debug, Serialize, Deserialize)]
pub struct HeuristicsListResponse {
pub heuristics: Vec<String>,
}
/// POST /heuristics
#[derive(Debug, Serialize, Deserialize)]
pub struct HeuristicsSubmitRequest {
pub package: PackageDescriptor,
pub heuristics_filter: Vec<String>,
pub include_deps:... | Rust | 0 |
fn load_linux(
config: &X86BootLoaderConfig,
sys_mem: &Arc<AddressSpace>,
fwcfg: &mut dyn FwCfgOps,
) -> Result<()> {
if config.kernel.is_none() {
setup_e820_table(config, sys_mem, fwcfg)?;
return Ok(());
}
let mut kernel_image = File::open(config.kernel.as_ref().unwrap().clone... | Rust | 0 |
getattr(self, "_cached_feat", None)
if z is None:
raise RuntimeError("forward() must be called before get_cached_feat()")
if clear:
self._cached_feat = None # clear cache
return z
if __name__ == "__main__":
# Example usage
model = DiT_BF2IF(
latent... | Python | 1 |
#!/usr/bin/env python3
"""
配置管理页面
"""
import streamlit as st
import pandas as pd
from datetime import datetime, timedelta
import plotly.express as px
import plotly.graph_objects as go
from typing import List
# 添加项目根目录到路径
import sys
from pathlib import Path
project_root = Path(__file__).parent.parent.parent
sys.path.i... | Python | 1 |
# Copyright (C) 2021 Hyunwoong Ko <kevin.brain@kakaobrain.com> and Sang Park <sang.park@dnotitia.com>
# All rights reserved.
# This is copied from dps [https://github.com/EleutherAI/dps]
# And modified by Hyunwoong Ko [https://github.com/hyunwoongko]
import re
from functools import partial
from typing import Tuple, L... | Python | 1 |
1<N, T, Store>>;
type SrcIter = Once<(ExtentN<N>, Self::Src)>;
fn read_extent(&'a self, extent: &ExtentN<N>) -> Self::SrcIter {
let in_bounds_extent = extent.intersection(self.extent());
once((in_bounds_extent, ArrayCopySrc(&self)))
}
}
impl<'a, N, T, Store> WriteExtent<N, ArrayCopySrc<&'... | Rust | 0 |
counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
let mut htlcs_to_fail = Vec::new();
let res = loop {
let mut channel_state_lock = self.channel_state.lock().unwrap();
let channel_state = &mut *channel_state_lock;
match channel_state.by_id.entry(msg.channel_i... | Rust | 0 |
{
Self {
orig: Vec3::zero(),
dir: Vec3::zero(),
}
}
pub fn new(o: Vec3, d: Vec3) -> Self {
Self { orig: o, dir: d }
}
pub fn orign(&self) -> Vec3 {
self.orig
}
pub fn direction(&self) -> Vec3 {
self.dir
}
pub fn at(&self... | Rust | 0 |
nic_queues;
extern crate nic_initialization;
pub mod test_e1000_driver;
mod regs;
use spin::Once;
use alloc::vec::Vec;
use alloc::collections::VecDeque;
use irq_safety::MutexIrqSafe;
use volatile::{Volatile, ReadOnly};
use alloc::boxed::Box;
use memory::{PhysicalAddress, MappedPages, create_contiguous_mapping};
us... | Rust | 0 |
###############################Display
st.plotly_chart(fig) ### the chart
st.write("The application using primarily LSTM but you can chose other models:")
with st.expander("Linear regression"):
from forecast_prediction.nvda_prediction import linear_regression_forecast
st.write("If you want ... | Python | 1 |
time::Duration;
use protobuf::repeated::RepeatedField;
use std::io::Read;
use super::*;
fn a_metric_family_name() -> String {
"MetricFamily".to_string()
}
fn a_metric_family() -> promo_proto::MetricFamily {
let mut family = promo_proto::MetricFamily::new();
family.... | Rust | 0 |
ght: Box::new(r),
})
}
}
}
fn make_binary(&mut self, b: ExprBinary) -> Expr {
if self.is_overflow(&b.attrs) {
return Expr::Binary(b);
}
let ExprBinary {
attrs,
left,
op,
right,
} = b... | Rust | 0 |
as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_display_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
impl fmt::Display for ATContext {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::... | Rust | 0 |
mk: ms4_735tlfu, tkv499zj_44: pzkky6z3tqf, kulglbmnfgy):
False
del lk1_rvix2nd
fxty6mjf9r3 = ndxx1fdhea1
nonlocal smrkuak1_5m
global ya3nu87po9o
'# difficulties_punches_electrolyte -> trick_relief_swing'
from am32m5jnyyi import rzspukujzka, kxzfdkqixjq as gge9mw_mffs, zaw7oqkt0t_, mzgw2zlrcu... | Python | 1 |
through the equivalent of os.fsdecode().
kwargs = {'encoding': sys.getfilesystemencoding(),
'errors': 'surrogateescape'}
try:
path = (cbook._check_and_log_subprocess(['kpsewhich', filename],
_log, **kwargs)
... | Python | 1 |
"""
This file is part of Criadex.
Criadex 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.
Criadex is distributed in the hope that it will b... | Python | 1 |
el)*),*
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! typeparam_gen_struct_hlp {
(PRIV struct $N:ident {$($fields:tt)*}) => {
struct $N {
$($fields)*
}
};
(PUB struct $N:ident {$($fields:tt)*}) => {
pub struct $N {
$($fields)*
}
}... | Rust | 0 |
"created_at": "2020-01-08T23:48:37.000-08:00",
"updated_at": "2020-01-08T23:50:21.000-08:00",
"url": "https://api.github.com/repos/octo-org/octo-repo/actions/workflows/161335",
"html_url": "https://github.com/octo-org/octo-repo/blob/master/.github/workflows/... | Rust | 0 |
D::PREFERRED_VECTOR_WIDTH_CHAR
| D::PREFERRED_VECTOR_WIDTH_SHORT
| D::PREFERRED_VECTOR_WIDTH_INT
| D::PREFERRED_VECTOR_WIDTH_LONG
| D::PREFERRED_VECTOR_WIDTH_FLOAT
| D::PREFERRED_VECTOR_WIDTH_DOUBLE
| D::PREFERRED_VECTOR_WIDTH_HALF
| D::NATIVE_VECTOR_WIDTH_CHAR
... | Rust | 0 |
NONCE.into(), expires).to_store()
}
fn conflict_nonce_store() -> MemoryAuthNonceStore {
let expires = AuthDateTime::restore(standard_now())
.expires(&ExpireDuration::with_duration(Duration::days(1)));
MemoryAuthNonceMap::with_nonce(NONCE.into(), expires).to_store()
}
fn standard_ticket_store() -> Memor... | Rust | 0 |
DeferredNow,
record: &flexi_logger::Record,
) -> Result<(), std::io::Error> {
let level = record.level();
write!(
writer,
"{} {} {} {} {} > {}",
now.now().format("%Y-%m-%dT%H:%M:%S%.3f"),
process::id(),
thread::current()
.name()
.unwrap_or(&for... | Rust | 0 |
_entries,
n_entries_total = self.entries.len(),
pointer = self.pointer.as_str(),
"reading…",
);
n_entries >= PAGE_SIZE
} {}
self.expire();
info!(n_actual_entries = self.entries.len(), "refreshed");
Ok(())
}
... | Rust | 0 |
on (str): The direction of trapping ('free to trap', 'trap to free').
rate (float): The trapping rate value.
Returns:
None
"""
match carriers.lower():
case 'electrons':
match direction.lower():
case 'free to trap':
... | Python | 1 |
{
dispatches.push(Box::new(One));
}
}
b.iter(|| {
for i in 0..ITERATIONS {
test::black_box(dispatches[i % VEC_SIZE].return_value());
}
})
}
#[bench]
fn refdyn_homogeneous_vec(b: &mut Bencher) {
let mut rng... | Rust | 0 |
sponse.defer(thinking=True)
page = random.randint(1, 604)
em = self.get_mushaf_image(page=page, show_tajweed=show_tajweed)
mushaf_ui_view = MushafNavigator(page, show_tajweed, interaction)
await interaction.followup.send(embed=em, view=mushaf_ui_view)
@by_ayah.error
@by_page.err... | Python | 1 |
let pa = self.get_unchecked_mut(a) as *mut _;
let pb = self.get_unchecked_mut(b) as *mut _;
ptr::swap(pa, pb);
}
/// Removes `entity` from the array and returns the `index` mapped to it.
pub fn remove(&mut self, entity: Entity) -> Option<usize> {
Some(self.get_mut(entity)?.take()?.... | Rust | 0 |
import os
import shutil
import re
from collections import defaultdict
from langchain_community.document_loaders.pdf import PyPDFLoader
from dotenv import load_dotenv
from fastapi import HTTPException, UploadFile, status
from langchain.prompts import PromptTemplate
from langchain.callbacks import AsyncIteratorCallbackHa... | Python | 1 |
# Copyright (c) 2022 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 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
methods" list inside
/// "package.metadata.risc0".
fn guest_packages(pkg: &Package) -> Vec<Package> {
let manifest_dir = pkg.manifest_path.parent().unwrap();
Risc0Metadata::from_package(pkg)
.unwrap()
.methods
.iter()
.map(|inner| get_package(manifest_dir.join(inner)))
.c... | Rust | 0 |
""" Padding Helpers
Hacked together by / Copyright 2020 Ross Wightman
"""
import math
from typing import List, Tuple
import torch.nn.functional as F
# Calculate symmetric padding for a convolution
def get_padding(kernel_size: int, stride: int = 1, dilation: int = 1, **_) -> int:
padding = ((stride - 1) + dilati... | Python | 1 |
for v in list_
)
return "&".join(output)
class MediaType:
def __init__(self, media_type_raw_line):
full_type, self.params = parse_header_parameters(
media_type_raw_line if media_type_raw_line else ""
)
self.main_type, _, self.sub_type = full_typ... | Python | 1 |
always)]
pub(crate) fn new(bits: u8) -> Self {
XTAL_TICK_NUM_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for XTAL_TICK_NUM_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `XTAL_TICK_NUM` ... | Rust | 0 |
# import openai
# import config
# openai.api_key = config.OPENAI_API_KEY
# def analyze_sentiment(text):
# response = openai.ChatCompletion.create(
# model="gpt-4o",
# messages=[
# {"role": "system", "content": "You are a helpful assistant."},
# {"role": "user", "content": f... | Python | 1 |
Polkadot,
Kusama,
Unknow,
}
impl Default for Network {
fn default() -> Self {
Network::Polkadot
}
}
impl From<&str> for Network {
fn from(name: &str) -> Network {
match name {
"polkadot" => Network::Polkadot,
"kusama" => Network::Kusama,
_ => Network::Unknow,
}
}
}
impl From... | Rust | 0 |
from binance.constants import BINANCE_SELL_ORDER, BINANCE_NUM_OF_DEAL_RETRY, BINANCE_DEAL_TIMEOUT
from binance.rest_api import generate_post_request
from data_access.internet import send_post_request_with_header
from utils.debug_utils import print_to_console, LOG_ALL_MARKET_RELATED_CRAP, get_logging_level
from utils... | Python | 1 |
use crate::KitsuneSpace;
use ::fixt::prelude::*;
use url2::url2;
fixturator!(
Urls;
curve Empty vec![];
curve Unpredictable {
let mut rng = ::fixt::rng();
let vec_len = rng.gen_range(0, 5);
let mut ret = vec![];
for _ in 0..vec_len {
ret.push(url2!("https://exa... | Rust | 0 |
II character at position {}", e.position()
))?;
}
if let Some(cycle) = attributes.local_attr("cycle") {
*disc.cycle_mut() = u8::from_str(cycle).ok()
.and_then(|r#u8| BCD::from_hex(r#u8).ok())
.ok_or_else(|| dfs_error!("incorrect cycle count; not valid 2-digit BCD"))?;
}
if let Some(boot... | Rust | 0 |
import unittest
from unittest import mock
from ...management.prompts import Prompts
class TestPrompts(unittest.TestCase):
def test_init_with_optionals(self):
t = Prompts(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
... | Python | 1 |
b, _) = e.node {
return b.clone()
}
}
}
if stmts.len() > 0 {
let n = stmts.len() - 1;
let s = stmts.remove(n);
stmts.push(s.add_trailing_semicolon())
}
mk().block(stmts)
}
pub fn with_stmts_opt<T>(opt: Option<WithStmts<T>>) -> WithStmts<Opt... | Rust | 0 |
Client::new(mock_server.uri(), None, None).unwrap();
let sess = sg
.authenticate_user("nbabcock", "iCd<PASSWORD>!ppl")
.await
.unwrap();
// We need a block of bytes large enough to span 2 chunks
let file_content: Vec<u8> = vec![0; (5 * 1024 * 1024) + 100 * ... | Rust | 0 |
ciphertext_and_tag_length: &mut u32,
) -> FfiOckamError {
*ciphertext_and_tag_length = 0;
handle_panics(|| {
check_buffer!(additional_data);
check_buffer!(plaintext);
let additional_data = unsafe {
core::slice::from_raw_parts(additional_data, additional_data_length as usi... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.