text string | label_name string | labels int64 |
|---|---|---|
#sig_name(#(#unpack_exprs),*)
}
};
let type_name = syn::Ident::new(on_type_name, proc_macro2::Span::call_site());
quote! {
impl PluginFunction for #type_name {
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> Result<Dynamic, Box<Ev... | Rust | 0 |
mask.dimensions() == img_size);
for (x, y, pixel) in mask.enumerate_pixels_mut() {
//if the pixel is in the rectangle set it to probably foreground
if x > rect.x && x < rect.x + rect.w &&//TODO better way to do this, maybe rect as a tuple of points?
y > rect.y && y < rect.y + rect.h
... | Rust | 0 |
ting over the message's sucessors
for &s in successors_graph_indexes {
let temp_successor_node: &mut Node = &mut self.G[s];
//Setting the delivered message's entry in the bstr to 0
temp_successor_node.bits.set(j, false);
//Check if the sucessor can be delivered
... | Rust | 0 |
# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. 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 requ... | Python | 1 |
force_contiguous: bool = True,
):
"""
Wrapper around safetensors `save_model` helper function, which allows for
saving compressed model to disk.
Note: The model is assumed to have a
state_dict with unique entries
:param model: model to save on disk
:param filename: filename location t... | Python | 1 |
println!(
"\nlen: {}, k: {}, insert: {}, iter: {}, wrong: {}\n",
len,
((len as f64) / rcp_k) as usize,
insert,
iter,
wrong
);
total_wrong += wrong;
... | Rust | 0 |
from .common import moulti_test
assert moulti_test
COMMAND = ['text-search.bash']
def test_search_bar(moulti_test):
bad_regex, good_regex = r'[aeiou', r'[aeiou]'
assert moulti_test(press=('/', *bad_regex)) # Regex + red pattern
assert moulti_test(press=('/', 'ctrl+r', *bad_regex)) # Plain + white pattern
assert m... | Python | 1 |
>> = [
WindowConfig {
period: 10,
quota_ratio: 1,
}
].to_vec();
}
// impl pallet_free_calls::Config for Test {
// type Event = Event;
// type Call = Call;
// type WindowsConfig = FreeCallsWindowsConfig;
// // TODO change this
// type ManagerOrigin = frame_system::EnsureRoot<AccountId>;
// }
// Build g... | Rust | 0 |
/// has the `L` property, it is an `LTR` label.
///
/// 2. In an `RTL` label, only characters with the `Bidi` properties `R`, `AL`,
/// `AN`, `EN`, `ES`, `CS`, `ET`, `ON`, `BN`, or `NSM` are allowed.
///
/// 3. In an `RTL` label, the end of the label must be a character with
/// `Bidi` property `R`, `AL`... | Rust | 0 |
u"\t<proprety name = 'verb' value = '%s'/>\n" % (self.verb)
for title in self.text.keys():
text += u"\t<proprety name = '%s' value = '%s'/>\n" % (title,
self.text[title])
for tense in listtense:
text += u"\t<tense name = '%s'>\n" % (tense)
for pronoun ... | Python | 1 |
from sympy.core.function import (Derivative as D, Function)
from sympy.core.relational import Eq
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.testing.pytest import raises
from sympy.calculus.euler import euler_equations as euler
def test_eu... | Python | 1 |
nt throws an error, the error message is returned.
"""
try:
return self.run(
command,
fetch,
parameters=parameters,
execution_options=execution_options,
include_columns=include_columns,
)
exce... | Python | 1 |
m_utf8(std::slice::from_raw_parts(target_ptr, target_len as usize)) {
Ok(target) => target,
Err(_) => return NOT_UTF8,
};
let f = dependencies as *mut F;
let f = &mut *f;
match f(source, target) {
None => return NOT_FOUND,
Some(id) => {
std::ptr:... | Rust | 0 |
"dox", doc(cfg(feature = "v1_20")))]
#[doc(hidden)]
impl FromGlib<ffi::GstGLConfigSurfaceType> for GLConfigSurfaceType {
unsafe fn from_glib(value: ffi::GstGLConfigSurfaceType) -> Self {
skip_assert_initialized!();
Self::from_bits_truncate(value)
}
}
#[cfg(any(feature = "v1_20", feature = "dox... | Rust | 0 |
", "6"),
("(gint) PK_EXIT_ENUM_LAST", "12"),
("(gint) PK_EXIT_ENUM_MEDIA_CHANGE_REQUIRED", "7"),
("(gint) PK_EXIT_ENUM_NEED_UNTRUSTED", "8"),
("(gint) PK_EXIT_ENUM_REPAIR_REQUIRED", "11"),
("(gint) PK_EXIT_ENUM_SKIP_TRANSACTION", "10"),
("(gint) PK_EXIT_ENUM_SUCCESS", "1"),
("(gint) PK_EXIT_... | Rust | 0 |
ry), Box::new(vec![FileNotifyChange::FileName]), true, 1024);
loop {
let results = watcher.watch().unwrap();
for r in *results {
tx.send(r).unwrap();
}
}
});
rx
}//! Smoke tests for 1060 pads.
#![cfg(feature = "imxrt1060")]
#[macro_u... | Rust | 0 |
: LocalFutureObj<'a, ()>) -> Result<(), SpawnError> {
// Safety: LocalSpawner is !Send and !Sync, so the future spawned will
// always remain local to the executor.
Ok(self
.0
.spawn_obj(unsafe { mem::transmute(future.into_future_obj()) }))
}
/// Spawn a `FutureO... | Rust | 0 |
::<String>());
return new_string;
}
/// The parameter weekday is true if it is a
/// weekday, and the parameter vacation is true
/// if we are on vacation. We sleep in if it is
/// not a weekday or we're on vacation. Return
/// true if we sleep in.
///
/// # Example
///
/// Basic Usage:
///
/// ```
///
/// ```
pu... | Rust | 0 |
::KeyImage::new();
source.set_data(bytes.to_vec());
match KeyImage::try_from(&source).unwrap_err() {
ConversionError::ArrayCastError => {} // Expected outcome.
_ => panic!(),
}
}
// Too many bytes should produce an ArrayCastError.
... | Rust | 0 |
parse(&format!("https://{}.cloud.thethings.network", region))
}
}
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TtnReconcileStatus {
pub observed_generation: u64,
pub state: String,
#[serde(default, skip_serializing_if = "... | Rust | 0 |
Filter;
}
extern "C" {
pub fn av_bsf_iterate(opaque: *mut *mut ::std::os::raw::c_void) -> *const AVBitStreamFilter;
}
extern "C" {
pub fn av_bsf_next(opaque: *mut *mut ::std::os::raw::c_void) -> *const AVBitStreamFilter;
}
extern "C" {
pub fn av_bsf_alloc(
filter: *const AVBitStreamFilter,
c... | Rust | 0 |
_recv().is_ok() {
if send_playhead_tx
.try_send((time::Instant::now(), current_music_frame_index as f64 / sample_rate as f64))
.is_err()
{
remani_warn!("Failed to send audio playhead"); // this isn't supposed to happen, but just... | Rust | 0 |
tore_true', help="Enable debug messages")
parser.add_argument("--unlock", action="store_true", help="Unlock LAF")
def key_transform(old_key):
new_key = ''
for x in range(32,0,-1):
new_key += chr(ord(old_key[x-1]) - (x % 0x0C))
return new_key
def key_xoring(key2_t, kilo_challenge):
key2_t_xor = ''
... | Python | 1 |
#
# Copyright 2018-2019 IBM Corp. 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 applicable law... | Python | 1 |
tes.io/crates/serde_closure">📦 Crates.io</a> │ <a href="https://github.com/alecmocatta/serde_closure">📑 GitHub</a> │ <a href="https://constellation.zulipchat.com/#narrow/stream/213236-subprojects">💬 Chat</a>
//! </strong></p>
//!
//! This l... | Rust | 0 |
protocol::api::RequestMessage;
use kf_protocol::api::ResponseMessage;
use kf_protocol::transport::KfCodec;
use flv_future_aio::net::AsyncTcpStream;
use crate::KfSink;
use crate::KfStream;
use super::KfSocketError;
/// KfSocket is high level socket that can send and receive kf-protocol
#[derive(Debug)]
pub struct Kf... | Rust | 0 |
# pandas_series_day1.py
# Author: Yorqinoy
# GitHub: https://github.com/yorqinoyyy
# Description: 15 Pandas Series examples — basics, indexing, operations, and cleaning.
import pandas as pd
import numpy as np
print("Pandas version:", pd.version)
# 1. Listdan Series yaratish
values = [10, 20, 30, 40]
s = pd.Series(va... | Python | 1 |
from typing import cast
import graphene
from .....account import models
from .....account.error_codes import AccountErrorCode
from .....permission.auth_filters import AuthorizationFilters
from .....thumbnail import models as thumbnail_models
from ....account.types import User
from ....core import ResolveInfo
from ...... | Python | 1 |
DE, related_name='batchs')
class Meta:
unique_together = [('number', 'warehouse', 'goods', 'team')]
class Inventory(Model):
"""库存"""
warehouse = ForeignKey('data.Warehouse', on_delete=CASCADE, related_name='inventories', verbose_name='仓库')
goods = ForeignKey('goods.Goods', on_delete=CASCADE,... | Python | 1 |
def test_ledits_pp_inversion_batch(self):
device = 'cpu'
components = self.get_dummy_components()
sd_pipe = LEditsPPPipelineStableDiffusion(**components)
sd_pipe = sd_pipe.to(torch_device)
sd_pipe.set_progress_bar_config(disable=None)
inputs = self.get_dummy_inversion_inputs(device)
sd_pipe.... | Python | 1 |
class PercentageError(Exception):
pass
class InvalidPercentageError(PercentageError):
def __init__(self):
super().__init__("Percentage is invalid")
class LessPercentageError(PercentageError):
def __init__(self):
super().__init__("The percentage is lesser than the cut-off. Please try again.... | Python | 1 |
vec![Addr::unchecked("exec_1"), Addr::unchecked("exec_2")],
executors: vec![Addr::unchecked("exec_1"), Addr::unchecked("exec_2")],
ask_fee_info: None,
bid_fee_info: None,
ask_required_attributes: vec!["ask_tag_1".into(), "ask_tag_2".into()],
... | Rust | 0 |
(cfg(target_feature = "avx2")))]
pub fn splat_m128d_s_m128d(a: m128d) -> m128d {
m128d(unsafe { _mm_broadcastsd_pd(a.0) })
}
/// Splat the 128-bits across 256-bits.
/// ```
/// # use safe_arch::*;
/// let a = m128i::from(1_i128);
/// let b: [i128; 2] = splat_m128i_m256i(a).into();
/// assert_eq!(b, [1_i128, 1]);
///... | Rust | 0 |
"characters___token_characters": 2,
"characters___num_token_characters": 8,
}
padding_lengths["field_with_dict___token_ids"] = 7
padding_lengths["field_with_dict___additional_key"] = 3
padding_lengths["words___tokens"] = 4
padding_lengths["characters___token_character... | Python | 1 |
#!/usr/bin/python3
""" Holds a function that convert a json string into python object """
import json
def from_json_string(my_str):
""" convert Json string into python Data structure and returns it """
python_object = json.loads(my_str)
return python_object
| Python | 1 |
acy,
keras.metrics.CategoricalAccuracy()
])
x = np.random.random((1, 3))
y = np.random.random((1, 3))
model.train_on_batch(x, y)
out = model.predict(x)
fd, fname = tempfile.mkstemp('.h5')
with h5py.File(fname, mode='r+') as h5file:
keras.models.save_m... | Python | 1 |
oses: bmap! {
ASSIGNMENT_PRUNE => Occurrences::OnceOrMore,
ASSIGNMENT_ASSETS => Occurrences::OnceOrMore
},
metadata: bmap! {
FIELD_PRUNE_PROOF => Occurrences::NoneOrMore
},
... | Rust | 0 |
# 编写代码,定义fix()函数,使用递归的方式打印破损区域的编号.
def fix(n):
print(n)
fix(n + 1)
fix(1) | Python | 1 |
Nes::new();
nes.set_rom(rom);
nes.run();
}
<reponame>hhandika/seq-finder
use clap::{App, AppSettings, Arg, ArgMatches};
use crate::finder;
pub fn get_cli(version: &str) {
let args = App::new("seq-finder")
.version(version)
.about("Find ngs sequence")
.author("<NAME> <<EMAIL>>")
... | Rust | 0 |
//Ensure
$crate::impl_properties!{
@struct [ $struct ]
@generic [ $($generics)* ]
@delegate [ $delegate_type ]
$(@exclude [ $($exclude_props)* ])?
$(@include [ $($include_props)* ])?
@bounds [ $($bounds)* ]
@trait_id Ensure [$crate::core]
@implement {
fn ensure_unvalidated(c: Self::Ens... | Rust | 0 |
if platform.system() == "Darwin": # macOS
print(" curl -fsSL https://ollama.com/install.sh | sh")
elif platform.system() == "Linux":
print(" curl -fsSL https://ollama.com/install.sh | sh")
elif platform.system() == "Windows":
print(" Download from: http... | Python | 1 |
index)
qubit_right = qubits_by_index.get(right_index)
qubit_left.create_pulse_channel(
auxiliary_devices=[qubit_right],
channel_type=ChannelType.cross_resonance,
frequency=5.5e9,
scale=50,
)
qubit_left.create_pulse_channel(
aux... | Python | 1 |
p#GSnGSn[ SX4XVU5 u p#GSnGSn[ SX4XVU5 u p#GSnGSn[ SX4XVU5 u p#GSnGSn[ SX4XVU5 u p#GSnGSn[ SX4XVU5 u p#GSnGSn[ SX4XVU5 u p#GSnGSn[ SX4XVU5 u p#GSnGSn[ SX4... | Python | 1 |
ilename>src/lm_ots/signing.rs
use crate::{
constants::{D_MESG, MAX_HASH_CHAIN_COUNT, MAX_HASH_SIZE, MAX_LMOTS_SIGNATURE_LENGTH},
hasher::HashChain,
lm_ots::parameters::LmotsAlgorithm,
util::{coef::coef, helper::read_and_advance},
};
use core::convert::TryInto;
use tinyvec::ArrayVec;
#[cfg(feature = "f... | Rust | 0 |
import numpy as np
def reverse_elastic_interpolation(B, A, t):
t = max(0,1-t)
return A + (B - A) * (1 - np.exp(-6 * t) * np.cos(3 * np.pi * t)) | Python | 1 |
o sistema.
Args:
uow(AbstractUnidadeDeTrabalho): Unidade de trabalho abstrata
id(str): Identificador do pagamento a ser alterado
novo_valor(float): Novo valor do pagamento
novo_metodo(MetodoPagamento): Novo método de pagamento
solicitante(dict): Usuário que está solicitando ... | Python | 1 |
Fr,
pub(crate) beta: E::Fr,
pub(crate) gamma: E::Fr,
pub(crate) delta: E::Fr,
/// Used to compute g^x.
pub(crate) g_pow: FixedBaseCurvePow<E::G1Projective>,
/// Used to compute h^x.
pub(crate) h_pow: FixedBaseCurvePow<E::G2Projective>,
/// Used to compute s^x.
pub(crate) s_pow: Fixed... | Rust | 0 |
)).skip(spaces());
let instruction = operation.and(operands);
// A comment will just consume everything else on the line.
let comment = token(';').and(many::<Vec<_>, _>(any()));
let assignment = ident().skip(spaces())
.skip(token('=').skip(spaces()))
.and(operand... | Rust | 0 |
or.refresh_teams_order.connect(self.refresh)
mediator.mirror_signal.connect(self.update_mirror_bar)
mediator.mirror_bar_kill_signal.connect(self.destroy_mirror_bar)
def retranslateUi(self):
self.mirror_count.retranslateUi()
self.hard_mirror.retranslateUi()
self.no_weekly_bon... | Python | 1 |
e!(
fmt,
"{}.{}.{}.{}",
self.octets[0],
self.octets[1],
self.octets[2],
self.octets[3]
)
}
}
#[cfg(feature = "std")]
impl From<std::net::Ipv4Addr> for Ipv4Addr {
fn from(ip: std::net::Ipv4Addr) -> Self {
Ipv4Addr::new(
... | Rust | 0 |
from GMM_GMR import GMM_GMR
from matplotlib import pyplot as plt
import numpy as np
if __name__ == "__main__":
data = np.loadtxt("data2.txt", delimiter=',')
gmr = GMM_GMR(4)
gmr.fit(data)
timeInput = np.linspace(1, np.max(data[0, :]), 300)
gmr.predict(timeInput)
fig = plt.figure()
fig.sup... | Python | 1 |
16 => Self::PreInitArray,
17 => Self::Group,
18 => Self::SymTabShNdx,
19 => Self::Num,
_ => Self::Any(bytes),
}
}
}
<filename>src/lib.rs
pub mod compiler;
mod instruction;
pub mod machine;
<filename>examples/json-c/rs/json_tokener.rs<gh_stars>0
e... | Rust | 0 |
import insightconnect_plugin_runtime
from insightconnect_plugin_runtime.telemetry import auto_instrument
from insightconnect_plugin_runtime.exceptions import PluginException
from .schema import CreateTicketInput, CreateTicketOutput, Input, Output, Component
# Custom imports below
import requests
class CreateTicket... | Python | 1 |
name: Vec<u8> = raw_name
.iter()
.take_while(|&element| *element != 0)
.cloned()
.collect();
let name = match from_utf8(trimmed_name.as_slice()) {
Ok(s) => {
if s.is_ascii() {
s.to_string()
} else {
... | Rust | 0 |
: SdfDirection,
#[doc = "A list of the allowed protocol(s) for this flow. If you want this flow to be able to use any protocol within the internet protocol suite, use the value `ip`. If you only want to allow a selection of protocols, you must use the corresponding IANA Assigned Internet Protocol Number for each pr... | Rust | 0 |
"xcup;": "\u22c3",
"xdtri;": "\u25bd",
"xfr;": "\U0001d535",
"xhArr;": "\u27fa",
"xharr;": "\u27f7",
"xi;": "\u03be",
"xlArr;": "\u27f8",
"xlarr;": "\u27f5",
"xmap;": "\u27fc",
"xnis;": "\u22fb",
"xodot;": "\u2a00",
"xopf;": "\U0001d569",
"xoplus;": "\u2a01",
"xotime;... | Python | 1 |
FP128,
PPC_FP128,
Label,
Integer,
Function,
Struct,
Array,
Pointer,
Vector,
Metadata,
X86_MMX,
Token,
}
// FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
// the HashStable trait. Normally DepGraph::with_task() calls are
// ... | Rust | 0 |
ine = line.split()
glove_vocab[line[0]] = np.array(line[1:]).astype(np.float)
return glove_vocab
def encode(self, text, special_token=True):
if special_token:
return [self.word2idx['CLS']] + [self.word2idx[word] if word in self.word2idx else self.word2idx['UNK'] for
... | Python | 1 |
from precise.skatervaluation.schurcomparisonutil.schurportpaperutils import gamma_comparison_and_plot
from precise.skaters.covarianceutil.covrandom import rnd_symm_cov
# Runs three experiments where gamma is varied and portfolio variance computed
RHO = 0.35 # Approx pairwise correlation
SEVERITY = 0.05 # I... | Python | 1 |
#!/usr/bin/env python3
"""
Test the fixed comprehensive battery status and success rate calculation.
This tests the integration between the comprehensive battery status function and the V2 Two-Level Cascading Filter system.
"""
import sys
import os
sys.path.append('/Users/chyeap89/Documents/energyanalysis')
import pa... | Python | 1 |
from fastapi import HTTPException
from app.schemas.chat_schema_v2 import ChatRequest, ChatAnswer, ChatResponse
from app.services.chat_service_v2 import chat_service
import uuid
from langsmith import traceable
from langsmith.run_helpers import get_current_run_tree
@traceable(name="Chat Controller V2", inputs={"질문": lam... | Python | 1 |
test_setup
.withdraw(
ZKSyncAccountId(2),
ETHAccountId(0),
Token(token),
&deposit_amount / BigUint::from(4u32),
&deposit_amount / BigUint::from(4u32),
)
.await;
let block = if blocks_processing == BlockProcessing::CommitAndVerif... | Rust | 0 |
}
}
mod codegen;
mod models;
mod train;
mod cache_fix;
pub mod optimizer;
pub use models::{RMITrainingData, RMITrainingDataIteratorProvider, ModelInput};
pub use models::KeyType;
pub use optimizer::find_pareto_efficient_configs;
pub use train::{train, train_for_size, train_bounded};
pub use codegen::rmi_size;
pub... | Rust | 0 |
import tensorflow as tf
import math
## refs:
### https://www.zhihu.com/question/50043438
### https://www.tensorflow.org/extras/candidate_sampling.pdf
## examples from:
# https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits
# https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross... | Python | 1 |
{
pub sender: Name,
pub sender_id: u128,
pub payer: Name,
pub trx_id: Checksum256,
pub packed_trx: Bytes<'a>,
}
// nodeos v2.0
#[derive(Debug, EosioDeserialize)]
pub struct ActivatedProtocolFeatureV0 {
pub feature_digest: Checksum256,
pub activation_block_num: u32,
}
// nodeos v2.0
#[deri... | Rust | 0 |
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
import collections
import operator
import functools
import itertools
from .abstract import Ordered
from .ordered_dict import OrderedDict
class _AbstractFrozenDict(collections.abc.Mapping):
_hash = None # Overridden by instanc... | Python | 1 |
# -*- coding: latin1 -*-
# Copyright (C) 2006-2010 João Luís Silva <jsilva@fc.up.pt>
#
# 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 2, or (at your option)
# any later vers... | Python | 1 |
pin we want to cause interrupts. To control
// which pins can cause an interrupt in the PCIE0 group, we have to set the Pin Change Mask 0
// (PCMSK0) accordingly. The documentation hints, that Pin 0 of PORTB corresponds to the
// Pin Change Interrupt 0, so let's enable that one.
PCMSK0::set(PCMSK0::PCI... | Rust | 0 |
Vec<Function>>,
}
impl Aggregator {
//structure Group by query string
// group
// term:name, example:?group=term(dept)
// range: range(field,min,0,20,30,40,max) ?group=range(age,min,0,20,30,40,max)
// data: data(field,yyyy-MM-dd) ?group=data(birthday,yyyy-MM-dd)
// aggs
// Stats(... | Rust | 0 |
detail = msg_infos[2]
msg_content['data'] = str_msg_all
msg_content['detail'] = detail
msg_content['desc'] = str_msg
else:
msg_content['data'] = content
if self.DEBUG:
try... | Python | 1 |
{json.dumps(context['ats_tips'], indent=2)}
Make each tip more specific, actionable, and personalized. Provide clear examples where helpful.
Keep ATS best practices in mind and ensure the advice helps the resume pass through ATS systems.
Return ONLY a JS... | Python | 1 |
token_type_ids=token_type_ids[:, TOKEN_LEN:],
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=None,
output_attentions=False,
output_attentions_scores=False,
... | Python | 1 |
from datetime import datetime as d
today = d.today()
birth_day = d(1991,9,11,15,00,00)
print(today.isoformat(sep=' ',timespec='seconds'))
print(birth_day.isoformat(sep=' ',timespec='seconds'))
diff = today -birth_day
print(diff)
#Extra
print("Extra")
#Format DD-MM-YYYY
print(f'{birth_day.day}-{birth_day.month}-{birt... | Python | 1 |
}
pub fn acosh(x: f64) -> f64 {
x.acosh()
}
pub fn acot(x: f64) -> f64 {
(1f64 / x).atan()
}
pub fn acoth(x: f64) -> f64 {
(1f64 / x).atanh()
}
pub fn acosec(x: f64) -> f64 {
(1f64 / x).asin()
}
pub fn acosech(x: f64) -> f64 {
(1f64 / x).... | Rust | 0 |
le 2D annotation record.
- file_name (str): flie name
- image_id (str): sample data token
- area (float): 2d box area
- category_name (str): category name
- category_id (int): category id
- bbox (list[float]): left x, top y, dx, dy of 2d box
... | Python | 1 |
import os
from langchain_community.chat_message_histories import RedisChatMessageHistory
from langchain.memory import ConversationBufferMemory
def get_memory(session_id: str):
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
chat_history = RedisChatMessageHistory(
session_id=session_id,
... | Python | 1 |
class Node:
def __init__(self, data):
self.data = data
self.next = None
def is_circular(head):
if head is None:
return False
temp = head.next
while temp is not None and temp != head:
temp = temp.next
return temp == head
head = Node(1)
second = Node(2)
third = Node(3... | Python | 1 |
e(),
texPath,
oldImg,
dstImg))
log.debug("Enabling shadeless rendering on body")
self.shadelessButton.setChecked(True)
self.human.setShadeless(1)
mh.redraw()
# This method is called when the plugin is loaded into makehuman
# The app refer... | Python | 1 |
= "MaxStaticMusicBitrate",
skip_serializing_if = "Option::is_none"
)]
pub max_static_music_bitrate: Option<i32>,
/// The content of the aggregationFlags element in the urn:schemas-sonycom:av namespace.
#[serde(
rename = "SonyAggregationFlags",
skip_serializing_if = "Option::is_n... | Rust | 0 |
1, ...].contiguous()
img = img[:, 0, ...].contiguous()
y_a = gt_label
y_b = gt_label[rand_index]
mask = rand_grid(lam, img.size(), cut_area_ratio, cut_aspect_ratio,
n_holes, hole_aspect_ratio)
img = img * (1 - mask) + img_ * mask
lam = 1 - (... | Python | 1 |
rWidth::U32 => "32",
PointerWidth::U64 => "64",
}
}
}
impl FromStr for PointerWidth {
type Err = Error;
/// Create a new `PointerWidth` from the given string
fn from_str(name: &str) -> Result<Self, Self::Err> {
let result = match name {
"16" => PointerWidth::U16... | Rust | 0 |
spaces};
#[derive(PartialEq)]
enum State {
First,
Rest,
Done,
}
pub struct MapAccess<'a, 'de: 'a> {
deserializer: &'a mut HzdataDeserializer<'de>,
state: State,
}
impl<'a, 'de: 'a> MapAccess<'a, 'de> {
pub(super) fn new(deserializer: &'a mut HzdataDeserializer<'de>) -> Self {
MapAcces... | Rust | 0 |
#!/usr/bin/env python3
"""
Helper functions and class for hypermedia pagination
"""
import csv
import math
from typing import List, Tuple
def index_range(page: int, page_size: int) -> Tuple[int, int]:
"""Calculate start and end indexes for pagination.
Args:
page: An integer representing the current p... | Python | 1 |
print(f"{args.path} missed, check repo path")
sys.exit(1)
if file_path:
if self.check_patch_applicable(file_path, repo_path):
self.apply_patch(file_path, repo_path)
else:
print(f"{file_path} patched in {... | Python | 1 |
'),
('Ana Duarte', 'Alinhamento da versão'),
('João', '9208 - Métricas de regressão'),
('João', '3769 - Regressão: Análise de Séries temporais'),
('João', 'Quais os algoritmos de clusterização e quando utilizar?'),
]
response = calendar_api.create_quarterly_planning_events_json(inst... | Python | 1 |
}
return {
"is_valid": len(errors) == 0,
"errors": errors,
"score": score,
"strength": strength_levels.get(score, "Unknown")
}
@staticmethod
def create_secure_hash(data: str, salt: Optional[str] = None) -> str:
"""Create a sec... | Python | 1 |
Half, RW),
Reg::new("PH42-020-S300-R", V1, "PositionDGain", 528, Half, RW),
Reg::new("PH42-020-S300-R", V1, "PositionIGain", 530, Half, RW),
Reg::new("PH42-020-S300-R", V1, "PositionPGain", 532, Half, RW),
Reg::new("PH42-020-S300-R", V1, "Feedforward2ndGain", 536, Half, RW),
Reg::new("PH42-020-S300... | Rust | 0 |
o_and_returns
for attr in portfolio._slots():
if attr[0] == "_":
try:
getattr(portfolio, attr[1:])
except AttributeError:
pass
getattr(portfolio, attr)
def test_portfolio_cache(portfolio_and_returns, periods, measure):
portfolio, returns ... | Python | 1 |
adversary = AutoAttack(model, norm='Linf', eps=8 / 255)
defense = sample_feature.SampleFeatureMLP(device, args.sample_path, args.feature_path, height=32, width=32)
clean_acc_lst = []
robust_acc_lst = []
for i in range(args.repeat):
print("==============")
logger.info("==============... | Python | 1 |
add(&schema).unwrap();
index.verify_references().unwrap();
let index = index.into_index();
let mut validator = Validator::new(&index);
let actual: TestMap = serde_json::from_value(reduce_tree(&mut validator, &curi, docs)).unwrap();
actual.add == expect
}
#[derive(Deserialize, Debug)]
#[serde(deny... | Rust | 0 |
ef_text
start_pos -= 1
alignment.add_component(
bx.align.maf.Component(
src="%s.%s%s" % (dbkey, ("chr" if not vc.chrom.startswith("chr") else ""), vc.chrom),
start=start_pos,
size=len(ref_text.replace("-", "")),
... | Python | 1 |
expect("Cannot create folder");
// #2
assert_eq!(
onedrive
.create_folder(ItemLocation::root(), folder_name)
.await
.expect_err("Re-create folder should fail by default")
.status_code(),
Some(StatusCode::CONFLICT),
);
// #3
assert_eq!... | Rust | 0 |
inactive and cannot be patched.
Inactive = 2,
/// The instance is notified that it should be patched.
Notified = 3,
/// The instance has started the patching process.
Started = 4,
/// The instance is downloading patches.
DownloadingPatches = 5,
/// The in... | Rust | 0 |
import wn
from wn import lmf
import pytest
@pytest.mark.benchmark(group="lmf.load", warmup=True)
def test_load(datadir, benchmark):
benchmark(lmf.load, datadir / 'mini-lmf-1.0.xml')
@pytest.mark.benchmark(group="wn.add_lexical_resource")
@pytest.mark.usefixtures('empty_db')
def test_add_lexical_resource(mock_l... | Python | 1 |
--
if __name__ == "__main__":
while True:
tampilkan_menu()
pilihan = input("Masukkan pilihan Anda (1/2/3/4): ")
if pilihan == '1':
cek_dan_bersihkan_path()
input("\nTekan Enter untuk kembali ke menu...")
elif pilihan == '2' or pilihan == '3':
... | Python | 1 |
from itertools import chain
from itertools import accumulate
def part1(diskmap):
files = [i for i, count in enumerate(diskmap[::2]) for _ in range(count)]
rlc_decoded = [i//2 if i % 2 == 0 else -1 for i, count in
enumerate(diskmap) for _ in range(count)]
sum_ = sum([i*element if elemen... | Python | 1 |
the data to work with
self.lock.acquire()
try:
mydata = self.deep_copy()
check_time = self.get_check_duration()
self.reset_state()
self.lock.release()
except LogtailerStateException, e:
# if something went wrong with deep_copy or the d... | Python | 1 |
,
clickCandidateCallback,
searchCallback)
# Add return button.
(returnButton, returnButtonAlign) = newActionButton(
"search", 1.0, 0.5, "cell", False, __("Return"), BUTTON_FONT_SIZE_MEDIUM, "bigButtonFont",
0, 10
)
returnButton... | Python | 1 |
"i_Pos"),
(1, "i_Scale"),
(2, "i_Color"),
(3, "i_BorderColor"),
(4, "i_BorderRadius"),
(5, "i_BorderWidth"),
],
)
};
let transform_location =
unsafe { gl.get_unif... | Rust | 0 |
}
impl SdramChip for Is42s16400j {
/// Value of the mode register
const MODE_REGISTER: u16 = BURST_LENGTH_1
| BURST_TYPE_SEQUENTIAL
| CAS_LATENCY_2
| OPERATING_MODE_STANDARD
| WRITEBURST_MODE_SINGLE;
/// Timing Parameters
const TIMING... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.