text string | label_name string | labels int64 |
|---|---|---|
&format_state_name(&self.name, "min"),
self.data_type.clone(),
true,
)])
}
fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
vec![self.expr.clone()]
}
fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
Ok(Box::new(MinAccumulator::t... | Rust | 0 |
import torch
import numpy as np
from sklearn.decomposition import PCA
def project_onto_direction(H, direction):
"""Project matrix H (n, d_1) onto direction vector (d_2,)"""
mag = np.linalg.norm(direction)
assert not np.isinf(mag)
return (H @ direction) / mag
def flip_direction(layer_hiddens, direct... | Python | 1 |
MENA13W {
_STIMENA13W { w: self }
}
#[doc = "Bit 12 - 12:12\\] Bit mask to enable tracing on ITM stimulus port 12."]
#[inline]
pub fn stimena12(&mut self) -> _STIMENA12W {
_STIMENA12W { w: self }
}
#[doc = "Bit 11 - 11:11\\] Bit mask to enable tracing on ITM stimulus port 11."]
... | Rust | 0 |
let thread_pred = end_predicate.clone();
threads.push(thread::spawn(move || {
let mut rng = Rng::seed_from_u64((seed + i) as u64);
count_in_distribution_sample(thread_pred, gen_distribution, n_samples_thread, &mut rng)
}));
}
let mut count: usize = threads.into_it... | Rust | 0 |
, case_name, message);
}
self.counters.inc_failed();
}
fn case_skipped(&mut self, suite: &TestSuite, case: &TestCase) {
if self.verbosity >= Verbosity::PassedSkippedFailed {
let suite_name = suite.description().unwrap_or_else(|| suite.name());
let case_name = ca... | Rust | 0 |
cable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -----------------------... | Rust | 0 |
/// * `path` - Path to a custom config file
pub fn load_config(path: Option<&str>) -> Result<Config, Box<dyn Error>> {
let str: String;
if path == None {
str = DEFAULT_CONFIG.to_string();
} else {
str = fs::read_to_string(path.unwrap())?.parse()?;
}
let conf: Config = serde_json::from_str(&str)?;
Ok(conf)
}
... | Rust | 0 |
str("min_base_pair_prob").unwrap().parse().unwrap()
} else {
DEFAULT_MIN_BPP
};
let min_align_prob = if matches.opt_present("min_align_prob") {
matches.opt_str("min_align_prob").unwrap().parse().unwrap()
} else {
DEFAULT_MIN_ALIGN_PROB
};
let gamma = if matches.opt_present("gamma") {
matches... | Rust | 0 |
res = []
for vect in self.texts_to_sequences_generator(texts):
res.append(vect)
return res
def texts_to_sequences_generator(self, texts):
'''
Transform each text in texts in a sequence of integers.
Only top "nb_words" most frequent words will be taken i... | Python | 1 |
NTO {} (server_id, prefix) VALUES (:server_id, :prefix)",
TABLE_PREFIX
),
params! {
"server_id" => server_id.0,
"prefix" => prefix,
},
)
.await?;
println!("Done.");
if let Some(prefix_cache) = ctx.data.read().await.get::<PrefixCache>() {
... | Rust | 0 |
import os
from designer.utils.utils import get_kd_data_dir, ignore_proj_watcher
from kivy.config import ConfigParser
from kivy.properties import ObjectProperty
from kivy.uix.settings import Settings
PROJ_DESIGNER = '.designer'
PROJ_CONFIG = os.path.join(PROJ_DESIGNER, 'config.ini')
class ProjectSettings(Settings):... | Python | 1 |
transpositions += 1.0;
}
b_match_index = j;
break;
}
}
}
if matches == 0.0 {
0.0
} else {
(1.0 / 3.0)
* ((matches / a_len as f64)
+ (matches / b_len as f64)
... | Rust | 0 |
mac_pms_constrain_sram_world_1_pms_3(
&mut self,
) -> SENSITIVE_DMA_APBPERI_MAC_PMS_CONSTRAIN_SRAM_WORLD_1_PMS_3_W {
SENSITIVE_DMA_APBPERI_MAC_PMS_CONSTRAIN_SRAM_WORLD_1_PMS_3_W { w: self }
}
#[doc = "Bits 16:17"]
#[inline(always)]
pub fn sensitive_dma_apbperi_mac_pms_constrain_sram_... | Rust | 0 |
, 36, 52, 5, 21, 37,
53, 6, 22, 38, 54, 7, 23, 39, 55, 8, 24, 40, 56, 9, 25, 41, 57, 10, 26, 42, 58, 11, 27,
43, 59, 12, 28, 44, 60, 13, 29, 45, 61, 14, 30, 46, 62, 15, 31, 47, 63,
];
Present80 {
n_rounds,
message_length,
key_length,
... | Rust | 0 |
from __future__ import annotations
__all__ = ["MENU_OFFSCR_REND_PARAM_ST"]
from soulstruct.base.params.param_row import *
from soulstruct.utilities.binary import *
class MENU_OFFSCR_REND_PARAM_ST(ParamRow):
CamAtPosX: float = ParamField(
float32, "camAtPosX", default=0.0,
tooltip="TOOLTIP-TODO",... | Python | 1 |
pub asm: BaselineAssembler<'a, 'ast>,
pub scopes: Scopes,
pub src: &'a mut FctSrc,
pub jit_info: JitInfo<'ast>,
pub lbl_break: Option<Label>,
pub lbl_continue: Option<Label>,
// stores all active finally blocks
pub active_finallys: Vec<&'ast Stmt>,
// label to jump instead of emit... | Rust | 0 |
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import climate, uart
from esphome import pins
from esphome.const import CONF_ID
CODEOWNERS = ["@gekkekoe"]
AUTO_LOAD = ["binary_sensor", "sensor", "text_sensor", "uart"]
CONF_ECODAN_ID = "ecodan_id"
CONF_PROXY_UART_ID = "prox... | Python | 1 |
result::{GetManyError, GetManyErrorKind};
#[allow(unused_imports)]
use std_proposal::{ErrorKind, Error, ErrorNiche, ErrorSimple};
pub type Elem = usize;
pub const LEN: usize = 3;
}
1: fn option_simple(
slice: &mut [Elem],
indices: [usize; LEN]
) -> Option<[... | Rust | 0 |
None, world.component::<i32>(Entity::new(0, Wrapping(0))));
}
#[test]
fn get_shared_empty_world() {
let universe = Universe::new(None);
let world = universe.create_world();
assert_eq!(None, world.tag::<i32>(Entity::new(0, Wrapping(0))));
}
}
#[macro_use]
extern crate clap;
ext... | Rust | 0 |
"C",
[aux1, aux2, dest_vertex.position],
)
)
else:
path.append(
format_path_step(
"L",
dest_vertex.position,
)
)
path = " ".join(path)
strok... | Python | 1 |
history for the final hop which is typically the target.
fn render_history<B: Backend>(f: &mut Frame<'_, B>, app: &mut TuiApp, rect: Rect) {
let target_hop = app.table_state.selected().map_or_else(
|| app.tracer_data().target_hop(),
|s| &app.tracer_data().hops()[s],
);
let data = target_hop... | Rust | 0 |
ous action space is supported")
raise NotImplementedError
# 对于策略动作的分布,主要是随机策略(例如sac算法中使用的policy)需要使用
# 对于随机策略输出的动作分布,常见的就是:TanhGaussDistribution,包括CleanRL中sac算法使用的也是这个
# 但是TanhGaussDistribution作为动作分布的优势体现在哪?特别地为什么要Tanh?这一点还不清楚
if kwargs["policy_act_distribution"] == "default":
# 如果没... | Python | 1 |
import sys
import os
class AndroidNDK:
"""
This class is used to get the current NDK information.
"""
ndk_dir = ""
def __init__(self, ndk_dir):
self.ndk_dir = ndk_dir
@property
def host_tag(self):
"""
Returns the host tag for the current system.
Note: The... | Python | 1 |
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.2'
_lr_method = 'LALR'
_lr_signature = '\x80\x98\x89\x82hgca\x8e\x92\x88\xee\xc9< \xc3'
_lr_action_items = {'H2':([0,11,],[2,2,]),'H3':([0,11,],[3,3,]),'H1':([0,11,],[4,4,]),'TEXT':([2,3,4,],[7,7,7,]),'CR':([5,6,7,8,9,10,12,],[1... | Python | 1 |
: StructFields,
}
// TODO - fn Struct::field_names()
// TODO - fn Struct::field_types()
/// Fields of a [`Struct`] or an [`EnumVariant`].
#[derive(Clone, Debug)]
pub enum StructFields {
Unit,
Tuple(Vec<TupleField>),
Named(Vec<NamedField>),
}
/// Declaration of an enum.
///
/// **Example input:**
///
/// ... | Rust | 0 |
highest value is valid
if array.iter().max() >= Some(&30000) { panic!("Invalid array.") }
// Check if the array size matches to the read array size
assert_eq!(asize, array.len());
// Find the number of inversions
let (inv, _) = solve(array);
println!("{}", inv);
}
}
// variables and mutabilit... | Rust | 0 |
import Foundation
from PyObjCTools.TestSupport import TestCase, min_os_level
class TestNSJSONSerialization(TestCase):
def test_enum_types(self):
self.assertIsEnumType(Foundation.NSJSONReadingOptions)
self.assertIsEnumType(Foundation.NSJSONWritingOptions)
@min_os_level("10.7")
def testCons... | Python | 1 |
import os
import logging
from flask import Flask
from urllib.parse import urlparse
from extensions import db, login_manager, socketio, bcrypt, jwt, talisman
# Configuration du logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def create_app():
"""
Fonction Factory pour crée... | Python | 1 |
![doc = include_str!("../README.md")]
#![recursion_limit = "1024"]
#![cfg_attr(test, allow(soft_unstable))]
#![cfg_attr(test, feature(test))]
#![cfg_attr(feature = "fn_traits", feature(fn_traits, unboxed_closures))]
#[cfg(test)] extern crate test;
#[macro_use]
extern crate derivative;
extern crate approx;
extern cra... | Rust | 0 |
from weaverbird.backends.mongo_translator.steps.types import MongoStep
from weaverbird.pipeline.conditions import (
ComparisonCondition,
Condition,
ConditionComboAnd,
ConditionComboOr,
DateBoundCondition,
InclusionCondition,
MatchCondition,
NullCondition,
)
from weaverbird.pipeline.dates... | Python | 1 |
liente
@param address Domicilio
@param doc Documento del cliente segn docType
@param docType Tipo de documento
@param ivaType Tipo de IVA
"""
raise NotImplementedError
def openReceipt(self, name, address, doc, docType, ivaType,... | Python | 1 |
#!/usr/bin/env python3
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.
# mypy: disable-error-code="no-untyped-def"
# heal... | Python | 1 |
} else {
crate::apu::LENGTH_TABLE[(self.regs[3] >> 3 & 0x1f) as usize]
}
}
fn halt(&self) -> bool {
self.regs[0] & 0x80 != 0
}
fn sequence(&self) -> u8 {
let table = [
15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 1, 2, 3, 4, 5, 6, 7,... | Rust | 0 |
: self as *const _ as u64,
};
unsafe {
llvm_asm!("lidt ($0)" :: "r" (&desc));
}
}
fn set_handler(&mut self, n: usize, handler: usize, flags: EntryFlags, ist: u8) {
self.0[n] = Entry::new(handler, flags, ist);
}
}
lazy_static! {
static ref IDT_INSTANCE: IDT ... | Rust | 0 |
}
Contact Number: {contact}
Language: {'Simplified Chinese' if lang == 'zh' else 'English'}
ClinicalTrials.gov Link: https://clinicaltrials.gov/study/{ctd_id}
Patient Information:
{patient_info}
Rules:
- Write in a polite and professional tone
- Express genuine interest in participating in the trial
- Mention that the... | Python | 1 |
=treasury_withdrawal_destination, has_one=auction_house_treasury)]
pub auction_house: Account<'info, AuctionHouse>,
pub token_program: Program<'info, Token>,
pub system_program: Program<'info, System>,
}
/// Accounts for the [`withdraw_from_fee` handler](auction_house/fn.withdraw_from_fee.html).
#[derive(... | Rust | 0 |
""" Set the image urls according to DocumentCloud conventions, assuming the whole slug thing is the document_slug
"""
import re
from dc_utils.url_helpers import parse_dc_slug, get_normal_image_url, get_thumbnail_image_url
from django.core.management.base import BaseCommand, CommandError
from documents.models import P... | Python | 1 |
: k for k, v in regex.groupindex.items()}
return [names.get(1 + i, i) for i in range(regex.groups)]
def str_extractall(arr, pat, flags=0):
regex = re.compile(pat, flags=flags)
# the regex must contain capture groups.
if regex.groups == 0:
raise ValueError("pattern contains no capture groups")
... | Python | 1 |
();
for slice in slices.iter().skip(1) {
let slice_reference_sequence_id = slice.header().reference_sequence_id();
if slice_reference_sequence_id != container_reference_sequence_id {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
... | Rust | 0 |
-> ::libc::c_longlong;
pub fn wcstoull(arg1: *const wchar_t, arg2: *mut *mut wchar_t,
arg3: ::libc::c_int) -> ::libc::c_ulonglong;
pub fn mbsnrtowcs(arg1: *mut wchar_t, arg2: *mut *const ::libc::c_char,
arg3: size_t, arg4: size_t, arg5: *mut mbstate_t)
-> size_t;
... | Rust | 0 |
RARequest] = None,
) -> AnyTokenizer:
return await self._local_tokenizer_group.get_lora_tokenizer_async(
lora_request)
def check_health(self):
if self._exception:
raise RuntimeError(
"TokenizerGroupPool is unhealthy.") from self._exception
def _carry_ov... | Python | 1 |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module containing commands related to the \
Information Superhighway (yes, Internet). """
import time
... | Python | 1 |
.button("Quit", |s| s.quit()),
);
}
fn game_tick(s: &mut cursive::Cursive, guess: &str) {
// Update game state
s.with_user_data(|game: &mut HangmanGame| {
game.enter_letter(String::from(guess));
});
// Clear input field
s.call_on_name("input", |view: &mut EditView| view.set_cont... | Rust | 0 |
.filter(|&(x, y, _)| state.get(&(x, y)).is_none())
.max_by(|(_, y1, _), (_, y2, _)| y1.cmp(y2));
if start_pos
.iter()
.filter(|(_, x, y)| (*x, *y) == *pos)
.count()
>= 1
{
if amphipod.1 {
vec![] // already at destination
} else {
... | Rust | 0 |
self,
dim,
head_dim,
ln_bias=False,
attn_qkv_bias=False,
attn_dropout=0.0,
attn_fc_bias=False,
attn_fc_dropout=0.0,
mlp_ratio=4,
mlp_bias=False,
mlp_dropout=0.0,
use_qk_norm=True,
):
super().__init__()
sel... | Python | 1 |
from aiogram import F, Router
from aiogram.types import Message
import logging
from bot import group_id
logger = logging.getLogger(__name__)
router = Router(name=__name__)
@router.message(F.chat.id.in_([group_id, -1001781118607]))
async def ignore_group_chat_all_messages(message: Message):
logger.info(
... | Python | 1 |
ded_request, args=(url,cj))
t.setDaemon(1) #Daemonize the thread
t.start() #start the thread
#Add support for gzip
opener.addheaders = [('Accept-encoding', 'gzip')]
def v_print(sent_d=0, received_d=0, received_d_pt=0,pings_n=0): #Verbose output for Debugging
global send
global received
global received_pt
glo... | Python | 1 |
# vim: set expandtab shiftwidth=4 softtabstop=4:
# === UCSF ChimeraX Copyright ===
# Copyright 2022 Regents of the University of California. All rights reserved.
# The ChimeraX application is provided pursuant to the ChimeraX license
# agreement, which covers academic and commercial uses. For more details, see
# <http... | Python | 1 |
import os, math
import numpy as np
def resolve_parallel_config():
enabled = os.getenv('HKGTFSPARALLEL', '1') == '1'
procs_env = os.getenv('HKGTFSPROCS')
try:
max_procs = int(procs_env) if procs_env else min(8, (os.cpu_count() or 1))
except ValueError:
max_procs = min(8, (os.cpu_count() ... | Python | 1 |
i - t, yhi, xhi - r[1], yhi) #top right
self.lineTo(xlo + r[0], yhi) #top row
if r[0]>0:
t = m*r[0]
self.curveTo(xlo + t, yhi, xlo, yhi - t, xlo, yhi - r[0]) #top left
self.lineTo(xlo, ylo + r[2]) #left edge
if r[2]>0:
t = m... | Python | 1 |
MOD = 10**9 + 7
class Solution:
def rectangleArea(self, rectangles):
# Step 1: Collect events (x, y1, y2, type)
events = [] # type: 1 = add, -1 = remove
ys = set()
for x1, y1, x2, y2 in rectangles:
events.append((x1, y1, y2, 1)) # rectangle starts
events.a... | Python | 1 |
test-host".to_string(),
display_name: Some("test-host".to_string()),
..Default::default()
}
);
}
#[test]
fn serialize_create_host_param() {
assert_eq!(
serde_json::to_value(&create_host_param_example()).unwrap(),
json_examp... | Rust | 0 |
ential(
latent_embed,
nn.Linear(latent_embed.out_channels, hidden_size - env_emb_dim),
)
self.proj = nn.Linear(in_channels - condition_dim, hidden_size)
seqTransEncoderLayer = nn.TransformerEncoderLayer(
d_model=hidden_size, nhead=4, batch_first=T... | Python | 1 |
定あり
if lora_name in modules_dim:
dim = modules_dim[lora_name]
alpha = modules_alpha[lora_name]
else:
# 通常、すべて対象とする
if is_lin... | Python | 1 |
(bytearray: [u8; 32]) -> String {
let mut result: String = "".to_string();
for byte in bytearray.iter() {
// Decide if you want upper- or lowercase results,
// padding the values to two characters, spaces
// between bytes, etc.
let s = format!("{}", *byte as u8);
result =... | Rust | 0 |
]
}
]
}
}
}
"""
acc = SocialAccount(
extra_data=loads(extra_data),
provider="linkedin_oauth2",
)
self.assertEqual("this-is-the-link", acc.get_avatar_url())
def test_id_missing(self):
extra_data = """
{
"profilePicture": {
"displ... | Python | 1 |
# -----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc. and Intake contributors
# All rights reserved.
#
# The full license is in the LICENSE file, distributed with this software.
# ----------------------------------------------------------------------... | Python | 1 |
ng/Dense0, D/Output
tgt_dict[name].copy_(update).requires_grad_(False)
else: # crop/pad
update = pad_up_to(src_dict[name], target_shape)
if a.verbose is True: print(name, source_shape, '=>', update.shape, '\n\n')
... | Python | 1 |
) => {
cb(GeneralStage::Insert(query));
}
proc::MSQueryStage::Delete(query) => {
cb(GeneralStage::Delete(query));
iterate_stage_expr(cb, &query.selection)
}
}
}
}
// -----------------------------------------------------------------------------------------------
// Tests... | Rust | 0 |
!= kitty_id_2, Error::<T>::RequireDifferentParent);
let kitty_id = Self::next_kitty_id()?;
let kitty_1_dna = kitty1.0;
let kitty_2_dna = kitty2.0;
let selector = Self::random_value(&sender);
let mut new_dna = [0u8; 16];
for i in 0..kitty_1_dna.len() {
new_dna[i] = combine_dna(kitty_1_dna[i], kitty_2_... | Rust | 0 |
rm-specific (though some flags like `RDONLY`, `NOEXEC`, and
/// `NOSUID` are common).Check the man pages for your OS of choice for more information.
#[cfg_attr(docsrs, doc(cfg(not(target_os = "netbsd"))))]
pub struct StatfsFlags: u64 {
#[cfg_attr(docsrs, doc(cfg(any(target_os = "linux", target_os = ... | Rust | 0 |
# core/chatgpt/extract_response.py
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from utils.waits import esperar_segundos
def obtener_respuesta(driver, timeout=30, poll_interval=1):
"""
Espera hasta que la respuesta de ChatGPT aparezca y luego la ex... | Python | 1 |
Parameters;
}
/// Interface that can be called from other modules.
pub trait API {
/// Perform an Ethereum CREATE transaction.
/// Returns 160-bit address of created contract.
fn create<C: TxContext>(ctx: &mut C, value: U256, init_code: Vec<u8>)
-> Result<Vec<u8>, Error>;
/// Perform an Ethere... | Rust | 0 |
ize>
where
<T as diesel::QuerySource>::FromClause: diesel::query_builder::QueryFragment<diesel::pg::Pg>,
{
let debug = diesel::debug_query::<diesel::pg::Pg, _>(&query).to_string();
aptos_logger::debug!("Executing query: {:?}", debug);
let res = query.execute(conn);
if res.is_err() {
let e = ... | Rust | 0 |
();
let store = InMemoryTrieStore::new(&env, None);
let data = &super::create_data()[0..1];
assert!(put_succeeds::<_, _, _, _, in_memory::Error>(&store, &env, data).is_ok());
}
#[test]
fn lmdb_put_succeeds() {
let tmp_dir = tempdir().unwrap();
let env = LmdbEnvironment::new(&tmp_dir.path().to_path... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Linjian Zhang
Email: linjian93@foxmail.com
Create Time: 2018-01-08 21:24:01
Program:
Description:
"""
import torch
import torch.nn as nn
from torch.nn.init import xavier_normal
def conv(batch_norm, c_in, c_out, ks=3, sd=1):
if batch_norm:
return ... | Python | 1 |
try:
from .serial_port import SerialPort
except:
SerialPort = None
from .socket_port import SocketPort
| Python | 1 |
Required features: `\"Win32_Security_AppLocker\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub fn SaferSetLevelInformation(levelhandle: super::SAFER_LEVEL_HANDLE, dwinfotype: SAFER_OBJECT_INFO_CLASS, lpquerybuffer: *const ::core::ffi::c_void, dwinbuffersize: u32) -> super::super::Foundati... | Rust | 0 |
process_progress = int(
(current_processing_chunk / total_chunks) * 50
)
playback_progress = int(
(current_playback_chunk / total_chunks) * 50
)
... | Python | 1 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
import time
import os
folder_name = "screenshots"
os.makedirs(folder_name, exist_ok=True)
#การเปิดหน้าเว็บโดยไม่ปิดเอง
op... | Python | 1 |
![Mode::Simple, Mode::Advanced];
let selection = Select::with_theme(&ColorfulTheme::default())
.items(&items)
.default(0)
.interact_on_opt(&Term::stderr())?;
let mode = selection.map_or(Mode::Simple, |index| items[index]);
let amount: usize = Input::new().wi... | Rust | 0 |
b3\x06\x5c\x13\x86\xde\x8eO\x1fI\xff\
\x00\x85\xb4\xb7TuCT\xd3\x93\x8b\xc32\x9d\x97\xb9\
k\xed\xedN5\xe1\x99[\xcf\xd1\xadK\xc2K\xed1\
\x8a\xb4\xf1\xcc\x85)\xe1\xe1\x99\xe9=\x13\xe9\xe4\xf1+\
&7\xf1C|k\xfam\xbe\xabaOT\xd2\xda\xa9\
B\xacx\x93\x89\x89\xd8]\xd5\xd3\xaf#$\xdai\x96\
\xee\xcf7g\xc0\xb7^\xf5\xbdnZmw\x89\xa7\xc... | Python | 1 |
// If successful, it returns a reservation that the sender can use to write data to the buffer.
/// Dropping the reservation signals completion of the write and makes the data available to the
/// reader.
///
/// ### Busy-waiting
///
/// If the current thread is scheduled on the same core as the... | Rust | 0 |
"""
Base cache interface for conversation caching.
This module defines the abstract base class for all cache implementations,
providing a consistent interface for caching operations.
"""
from abc import ABC, abstractmethod
from typing import Optional, Any, List
class BaseCache(ABC):
"""Abstract base class for c... | Python | 1 |
#!/usr/bin/python
#
# Convert instances from png files to a dictionary
# This files is created according to https://github.com/facebookresearch/Detectron/issues/111
from __future__ import print_function, absolute_import, division
import os, sys
sys.path.append( os.path.normpath( os.path.join( os.path.dirname( __file_... | Python | 1 |
true {
let foo = "";
return Ok(&foo[0..]);
} else if false {
let foo = "bar";
return Ok(&foo[0..]);
} else {
let foo = "";
return Ok(&foo[0..]);
}
if true {
let foo = "";
return Ok(&foo[0..]);
} else if false {
let foo = "bar"... | Rust | 0 |
ere
D: 'static + QueryDispatcher,
{
Self {
query_dispatcher: Arc::new(d),
quadtree: SimdQuadTree::new(),
tree_built: false,
dilation_factor: 0.01,
}
}
/// Update the acceleration structure on the query pipeline.
pub fn update(&mut ... | Rust | 0 |
start_m,
H // num_kv_groups,
BLOCK_M, HEAD_DIM, BLOCK_N,
4 - STAGE, offs_m, offs_n
)
acc = acc / l_i[:, None]
tl.store(O_block_ptr, acc.to(Out.type.... | Python | 1 |
len(labels) + 1)))
id2label = dict(zip(range(1, len(labels) + 1), labels))
id2label[0] = self.PADDING
label2id[self.PADDING] = 0
with open(self.label2id_file, 'w', encoding='utf-8') as outfile:
for idx in id2label:
outfile.write(id2label[idx] + '\t' + str(idx... | Python | 1 |
,
))
} else {
Err(Error::StreamExpected(self.offset))
}
}
#[doc = "Decodes and returns the next SPIR-V word as\na SPIR-V FPFastMathMode value."]
pub fn fp_fast_math_mode(&mut self) -> Result<spirv::FPFastMathMode> {
if let Ok(word) = self.word() {
... | Rust | 0 |
"SELECT EXISTS(SELECT 1 FROM new_members WHERE guild_id = $1)",
guild_id.0 as i64
)
.fetch_one(&pool)
.await?;
if channel_data.exists.unwrap() {
sqlx::query!(
"UPDATE new_members SET channel_id = $1 WHERE guild_id = $2",
channel_id.0 as i64,
gui... | Rust | 0 |
Esperanto.to_string(), "Esperanto".to_owned());
}
#[test]
fn test_esperanto_1() {
test_expected_language(
Lingo::new(),
"<NAME>, naskiĝis kiel <NAME> (* 29-a de marto 1968 en Mount Albert, Nov-Zelando) estas novzelanda aktorino.",
Language::Esperanto
... | Rust | 0 |
x,
data,
postfix,
})
}
// find first cesu8-start,
// find tail
// determine in-between
#[allow(clippy::ptr_arg)]
pub(crate) fn split_off_orphaned_bytes(cesu8: &Vec<u8>) -> CharLobSlice {
let mut split = 0;
for start in 0..cesu8.len() {
split = match cesu8_char_type(cesu8, start, ces... | Rust | 0 |
ng rules
let epsilon_k_sf =
(fluid_parameters.epsilon_k_ff() * *epsilon_k_ss).mapv(|e| e.sqrt());
let sigma_sf = (fluid_parameters.sigma_ff() + *sigma_ss) * 0.5;
epsilon_k_sf[i]
* ((sigma_sf[i] / z_grid).m... | Rust | 0 |
ut) = output {
i.items.push(ImplItem::Type(
syn::parse2(quote! { type Output = #output; }).unwrap(),
));
}
}
}
visit_mut::visit_item_impl_mut(self, i)
}
}
#[derive(Copy, Clone, PartialEq, Eq)]
enum Kind {
Fn,
FnMut,
FnOnce,
}
impl Kind {
fn name(self) -> &'static str {
match self {
... | Rust | 0 |
Map {
entries: 0,
has_val: 0,
arr: [ptr::null(); 15],
kv: PhantomData,
}
}
}
impl<'r, K: Hash + Eq + Clone + Trace, V: Clone + Trace> HashMap<'r, K, V> {
pub fn get(&'r self, key: &K) -> Option<&'r V> {
let mut hasher = FxHasher::default();
... | Rust | 0 |
', '\u{73e}', '𝁣', '\u{e0033}', '🗹', '⦯', 'ꤹ', '😾',
'𑐖', '⠥', 'ꃕ', 'ퟔ', '𓀎', '🏻', '㍵', 'F', 'ꐐ', '𖨫', 'R', '𝗘',
'᭖', '᧿', '👇', '᪗', '⍦', '🌀', '𐛹', '𐑹', 'ꊥ', '𘦫', 'ꨊ', '𐎳',
'ḹ', '𞺗', '𐅛', '\u{e0167}', '⣝', 'ﴤ', '𘦑', '𔑝', '\u{1b02}', '\u{18b73}',
'ꛮ', '👤', '𖥵', '𑩝', 'ꅛ', '\u{1da25}', ... | Rust | 0 |
"""
Module containing the RuleResult class for storing rule evaluation results.
"""
from typing import Dict, List, Any, Optional
from rule_engine.core.failure_info import FailureInfo
class RuleResult:
"""Class to store the result of a rule evaluation"""
def __init__(self, rule_name: str, success: bool, mes... | Python | 1 |
import os
import setuptools
readme_filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md")
with open(readme_filepath, "r", encoding="utf8") as fh:
long_description = fh.read()
version_filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "VERSION")
with open(version_filepat... | Python | 1 |
(
blank=True,
default="images/products/default.png",
upload_to="images/products/%Y/%m/%d",
validators=[
django.core.validators.FileExtensionValidator(
allowed_exten... | Python | 1 |
;
},
}
}
// This test should fail because
// ext.schedule.wasm.as_mut().unwrap().have_gasleft = false;
#[test]
fn gasleft_fail() {
let _ = ::env_logger::try_init();
let mut params = ActionParams::default();
params.gas = U256::from(100_000);
params.code = Some(Arc::new(load_sample!("gasleft.wasm")));
let mut e... | Rust | 0 |
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from math import ceil
from matplotlib.ticker import MultipleLocator
from local_utils.variables import CROPS, S2_BANDS
def plot_spectral_imp(crop_ds,crop_id,save_dir,now,logger):
"""BarPlot of the spectral impor... | Python | 1 |
reeRef<T> = Rc<RefCell<Tree<T>>>;
#[derive(Debug)]
pub enum Tree<T> {
Leaf(T),
NonLeaf {
left: SubtreeRef<T>,
right: SubtreeRef<T>,
},
}
impl<U: Default> TreeBuilder<U> for Tree<U> {
type Tree = Tree<U>;
fn leaf(value: U) -> Tree<U> {
Tree::Leaf(value)
}
fn non_leaf(left: Tree<U>, right: Tr... | Rust | 0 |
e
Usage:
avg_price --list=<astr>
avg_price (-h | --help)
avg_price --version
Options:
-h --help Show usage info.
--version Show version.
--list=<astr> List of shares with prices in the form \"s1,p1;s2,p2\"
";
fn main()
{
let args = Docopt::new(USAGE)
.and_then(|dopt| dopt.parse())
... | Rust | 0 |
ursuperior", "16785524"),
("GDK_KEY_fourthroot", "16785948"),
("GDK_KEY_function", "2294"),
("GDK_KEY_g", "103"),
("GDK_KEY_gabovedot", "757"),
("GDK_KEY_gbreve", "699"),
("GDK_KEY_gcaron", "16777703"),
("GDK_KEY_gcedilla", "955"),
("GDK_KEY_gcircumflex", "760"),
("GDK_KEY_grave", "9... | Rust | 0 |
progress_bar.update()
if callback is not None and index % callback_steps == 0:
step_idx = index // getattr(self.scheduler, "order", 1)
callback(step_idx, t, batch_inference_latents)
... | Python | 1 |
from plotnine import (
ggplot, aes, geom_point, facet_wrap, scale_x_log10, theme, element_text,
geom_text, theme_set, theme_gray, element_blank, facet_grid, stat_smooth
)
from pandas import DataFrame
import json
theme_set(theme_gray(base_family="Inter"))
# LAYER
with open("data/elapse_per_layer.json") as f:
... | Python | 1 |
reconstructed candidate tree
tw.write_candidates(&t)?;
Ok(())
}
<gh_stars>10-100
use super::*;
use std::sync::Arc;
pub mod state;
pub mod remote_state;
pub trait Data<T> {
fn with<R>(f: impl FnOnce(T)->R)->R;
}
pub struct SizeCache<E> where E: Env {
c: Option<ESize<E>>,
}
impl<E> SizeCache<E> wher... | Rust | 0 |
# Copyright 2024 Marcus Furlong <furlongm@gmail.com>
#
# This file is part of Patchman.
#
# Patchman 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, version 3 only.
#
# Patchman is distributed in the hope that... | Python | 1 |
from typing import List
# Coin Change
# Dynamic Programming
# Time: O(n*c)
# Space: O(n)
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
# number of coins
n = len(coins)
# sort for faster break
coins.sort()
# Dynamic Programming array to store the minimum... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.