text string | label_name string | labels int64 |
|---|---|---|
tity).unwrap().global_z,
(
&*entities,
&ui_transforms,
interactables.maybe(),
!&hiddens,
!&hidden_props,
)
... | Rust | 0 |
WHERE training_id = ?
"""
cursor.execute(query, update_values)
conn.commit()
logger.info("訓練進度更新成功: %s", training_id)
return True
return False
except Exception as e:
logge... | Python | 1 |
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownSymbol(s) => write!(f, "Unknown symbol: {}", s),
Self::GlobalExists(s) => write!(f, "Global already exists: {}", s),
Self::NonFunction(o) => write!(f, "Attempt to call non-function: {}", o),
... | Rust | 0 |
import streamlit as st
import datetime
from commons import CommonObjects
st.set_page_config(
page_title="Capi-API DEMO",
page_icon="Logo.png",
layout="wide",
initial_sidebar_state="expanded"
)
CommonObjects.header()
st.header("Conversion API (CAPI) ❄️ App - DEMO")
st.write("""
This Native Applic... | Python | 1 |
import cv2
import torch
import os
import numpy as np
from collections import Counter, deque
from ultralytics import YOLO
from deepface import DeepFace
from scipy.spatial.distance import cosine
import pickle
import warnings
import tensorflow as tf
import matplotlib.pyplot as plt
from io import BytesIO
import time
from f... | Python | 1 |
"""
Classifies: CHEBI:35757 monocarboxylic acid anion
"""
from rdkit import Chem
def is_monocarboxylic_acid_anion(smiles: str) -> tuple[bool, str]:
"""
Determines if a molecule is a monocarboxylic acid anion based on its SMILES string.
A monocarboxylic acid anion contains a single deprotonated carboxyl gro... | Python | 1 |
map_model::Map) -> Vec<String> {
let b = map.get_b(self.id);
let mut lines = vec![
format!("Building #{:?} (from OSM way {})", self.id, b.osm_way_id),
];
lines.extend(b.osm_tags.iter().cloned());
lines
}
pub fn get_bbox(&self) -> Rect {
geometry::get_... | Rust | 0 |
ap().distance(residues_a[jj].get_CA().unwrap());
}
}
for ii in 0..residues_b.len(){
for jj in 0..residues_b.len(){
dist_b[ii][jj] = residues_b[ii].get_CA().unwrap().distance(residues_b[jj].get_CA().unwrap());
}
}
//let res_:Option<DistanceAlignmentResult>... | Rust | 0 |
# Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from mmagic.apis.inferencers.translation_inferencer import \
TranslationInferencer
from mmagic.utils import register_all_modules
register_all_modules()
def test_translation_inferencer():
cfg = osp.join(
osp.dirname(__file__), '..'... | Python | 1 |
::new(library_path);
match linker.load(&path, &path) {
Ok(()) => (),
Err(err) => {
eprintln!("ld.so: failed to load '{}': {}", path, err);
unistd::_exit(1);
loop {}
}
}
let entry = match linker.link(Some(&path)) {
Ok(ok) => match ok {
... | Rust | 0 |
}
pub fn shift_right(&mut self) -> u8
{
let less_significant = self.value & 0x1;
self.value >>= 1;
return less_significant;
}
}
#[cfg(test)]
mod tests
{
use super::*;
#[test]
fn test_i_register()
{
let mut i_register = IRegister::new();
assert_... | Rust | 0 |
def allowed_moves(start, visited, N):
x, y = start//N, start%N
moves = [(x+2, y+1), (x+2, y-1), \
(x+1, y+2), (x+1, y-2), \
(x-1, y+2), (x-1, y-2), \
(x-2, y+1), (x-2, y-1)]
return [x*N + y for (x, y) in moves if x>=0 and y>=0 and x<N and y<N and \
x*N + ... | Python | 1 |
id diagram: graph.mermaid")
# Also print the diagram to console
print("\nMermaid diagram:")
print(mermaid_code)
except Exception as e:
print(f"Could not generate Mermaid diagram: {e}")
# Fallback to ASCII representation
try:
print("\nGrap... | Python | 1 |
;
let arg1 = tail.car()?;
match (arg0, arg1) {
(Atom(Number(n0)), Atom(Number(n1))) => Ok((f(n0, n1)).into()),
(Atom(Number(_)), e) | (e, _) => Err(Error::Type {
expected: "number",
given: e.type_of().to_string(),
... | Rust | 0 |
::errors::ParseEnumError;
use std::io::{Write, Read, Seek, BufRead};
use std::str::FromStr;
use jpeg_encoder::{Encoder, SamplingFactor, ColorType, EncodingError as JpegEncodingError};
use jpeg_decoder::{Decoder, PixelFormat, Error as DecoderError};
use crate::utils::{to_rgb8_vec, to_l8_vec, from_u8, cmyk_to_rgb};
us... | Rust | 0 |
a, Result<()>>;
fn insert_all<'a, I>(&'a mut self, iter: I, track: &'a E::TrackCtx) -> BoxFuture<'a, Result<()>>
where
I: IntoIterator<Item = (E::Key, E)> + Send + 'a,
I::IntoIter: Send,
Self: Send,
{
Box::pin(async move {
for (k, v) in iter {
sel... | Rust | 0 |
ERSION
// let mut next_value = move || {
// samples.next().unwrap()
// };
/////// SINE OSC VERSION
// let stream_config = StreamConfig {
// channels: config.channels,
// sample_rate: config.sample_rate,
// buffer_size: BufferSize::Fixed(mixer.chunk_size),
// };
... | Rust | 0 |
ics: TransferCharacteristics,
pub matrix_coefficients: Option<MatrixCoefficients>,
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum ColorInfoPrimary {
#[serde(rename = "COLOR_PRIMARIES_BT709")]
BT709,
#[serde(rename = "COLOR_PRIMARIES_BT2020")]
BT2020,
}
#[deri... | Rust | 0 |
############################
## API
#####################################################################
def implement_api(router: APIRouter, api: APIConcept[TArg, TResp]):
def process(
process_func: (
Callable[[TArg, Any], Coroutine[Any, Any, TResp]]
| Callable[[TArg], Coroutine[... | Python | 1 |
class Solution:
def equalFrequency(self, word: str) -> bool:
count = collections.Counter(word)
# Try to remove each letter, then check if the frequency of all letters in
# word are equal
for c in word:
count[c] -= 1
if self._equalCount(count):
return True
count[c] += 1
... | Python | 1 |
ak_plan(bp, deterministic=deterministic)
return pak_plan, to_plan_dict(pak_plan)
def inspect_pak(path: str | Path) -> dict: # implemented
return _inspect_pak_impl(str(path))
def validate_spec(path: str | Path) -> None: # placeholder minimal
logger = get_logger()
spec = load_models(path)
logger... | Python | 1 |
* 1000), # Current time in milliseconds
'sender_id': sender_id,
'message_text': message_text,
'sender_role': sender_role
}
# Add the new message to the 'messages' subcollection
new_message_ref = conversation_ref.child('messages').push(new_message)
#... | Python | 1 |
_meta_class = hooks.manage_obj(Class::bare(
hooks.manage_str(format!("{} metaClass", &*object_class.name())),
));
object_meta_class.inherit(hooks, class_class);
object_meta_class.set_meta(class_class);
object_class.set_meta(object_meta_class);
Class::with_inheritance(hooks, hooks.manage_str(... | Rust | 0 |
string + '\x1b[0m' : string;
}
function _Debug_numberColor(ansi, string)
{
return ansi ? '\x1b[95m' + string + '\x1b[0m' : string;
}
function _Debug_stringColor(ansi, string)
{
return ansi ? '\x1b[93m' + string + '\x1b[0m' : string;
}
function _Debug_charColor(ansi, string)
{
return ansi ? '\x1b[92m' + string + ... | Rust | 0 |
from sympy.core.function import (Derivative, Function, diff)
from sympy.core.symbol import symbols
from sympy.functions.elementary.trigonometric import sin
from sympy.core.multidimensional import vectorize
x, y, z = symbols('x y z')
f, g, h = list(map(Function, 'fgh'))
def test_vectorize():
@vectorize(0)
def ... | Python | 1 |
)
assert len(string_list_b) == len(block_flag_b)
return string_list_a, string_list_b, block_flag_a, block_flag_b
elif self.pattern_id == 4:
string_list_a = [text_a, "I", "thought", "it", "was", self.mask, "."]
string_list_b = []
block_flag_a = [0, 1, 1... | Python | 1 |
#[cfg(any(feature = "alloc", feature = "std"))]
impl<'a> From<&'a String> for $name<'a> {
fn from(str: &'a String) -> Self {
Self {
bytes: str.as_bytes(),
}
}
}
impl<'a> core::hash::Hash for $name<'a> {
... | Rust | 0 |
ename StatusCode");
env.set_field(state_obj, "message", "Ljava/lang/String;", JValue::Object(JObject::from(env.new_string(msg.to_string()).unwrap()))).expect("set message value ");
}
}
*state_obj
}
<reponame>komaeda/rust
#![allow(dead_code)]
use std::cell::Cell;
#[derive(Copy, Clone)]
st... | Rust | 0 |
"""
This module contains unit conversion constants and functions
"""
__author__ = 'Danny Broberg, Bharat Medasani'
__email__ = 'dbroberg@gmail.com, mbkumar@gmail.com'
import math
import numpy as np
import warnings
# Define conversion_constants
hart_to_ev = 27.2114
ang_to_bohr = 1.8897
invang_to_ev = 3.80986
kb = 8.... | Python | 1 |
SDT,
initial_btc,
initial_usdt,
Permill::zero(),
Permill::zero(),
);
let pool = get_pool(pool_id);
prop_assert_ok!(Tokens::mint_into(USDT, &BOB, usdt_value));
prop_assert_ok!(Tokens::mint_into(BTC, &BOB, btc_value));
prop_assert_ok!(Pablo::add_liquidity(Origin::signed(BOB), pool_id, btc_value, usd... | Rust | 0 |
# encoding=utf-8
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
from pylab import * #支持中文
# mpl.rcParams['font.sans-serif'] = ['SimHei']
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
#从pyplot导入MultipleLocator类,这个类用于设置刻度间隔
acc_sani = [
0.606896552,
0.517241379,
0.682... | Python | 1 |
) = cmd.get(NOTIFY_SCAN_FINISH) {
self.accept = true
}
}
_ => {}
}
}
fn lifecycle(
&mut self,
_ctx: &mut druid::LifeCycleCtx,
_event: &druid::LifeCycle,
_data: &AppState,
_env: &Env,
) {
}
f... | Rust | 0 |
=> OwnedPointer,
ast::ManagedSigil => OtherPointer,
}
}
_ => {
NotPointer
}
}
}
fn guarantor_of_deref(cat: &ExprCategorization) -> Option<ty::Region> {
match cat.pointer {
NotPointer => cat.guar... | Rust | 0 |
os = "android"
))]
#[pyfunction]
fn sched_getparam(pid: libc::pid_t, vm: &VirtualMachine) -> PyResult<SchedParam> {
let param = unsafe {
let mut param = std::mem::MaybeUninit::uninit();
if -1 == libc::sched_getparam(pid, param.as_mut_ptr()) {
return Err(errno_... | Rust | 0 |
0).select(
f32x8::splat(1.0)
- f32x8::splat(1.0).min((f32x8::splat(1.0) - $dst_b) / $src_b),
$src_b.eq(f32x8::splat(0.0)),
),
],
BlendMode::HardLight => [
($dst_r * $src_r * f32x8::splat(2.0)).select(... | Rust | 0 |
ck()
step.source_path = 'foo.fake'
step.index = 0
project = MagicMock()
project.steps = [step, MagicMock()]
result = source._execute_step(project, step)
assert not result['success']
project.steps[-1].mark_dirty.assert_called_once_with(True)
@patch('cauldron.runner.source.time.sleep')
@pa... | Python | 1 |
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
.into_pointer_value();
let length_pointer = builder.build_struct_gep(pointer_value, 1, "string-len-ptr").unwrap();
builder.build_load(length_pointer, "str-len").as_basic_value_enum()
} else {
panic!()
}
}
}
}
#[derive(Clone, Copy)]
pub... | Rust | 0 |
{
1 => ::std::option::Option::Some(PinMatrixRequest_PinMatrixRequestType::PinMatrixRequestType_Current),
2 => ::std::option::Option::Some(PinMatrixRequest_PinMatrixRequestType::PinMatrixRequestType_NewFirst),
3 => ::std::option::Option::Some(PinMatrixRequest_PinMatrixRequestType::Pi... | Rust | 0 |
#!/usr/bin/env python3
import tkinter as tk
# --- init ---
root = tk.Tk()
root.title('Pack')
# --- text ---
text = '\n[very, very, very, very, very long text for example]'
# --- info ---
tk.Label(root, text="Bartłomiej 'furas' Burek (blog.furas.pl)", bg='black', fg='white', width=70).pack()
tk.Label(root, text="... | Python | 1 |
").unwrap(),
b"\x06\x03\x81\x34\x03",
),
]);
}
#[test]
fn test_write_bit_string() {
assert_writes::<BitString>(&[
(BitString::new(b"", 0).unwrap(), b"\x03\x01\x00"),
(BitString::new(b"\x80", 7).unwrap(), b"\x03\x02\x07\x80"),
(... | Rust | 0 |
{'error': '服务类型必须是docker或host'}), 400
# 加载当前配置
current_config = load_config()
# 检查端口是否已存在,适配新的数据结构
existing_service = None
for service, config_value in current_config.items():
existing_port = None
if is... | Python | 1 |
s))
}
}
impl core::ops::Deref for SPIM_SSI_RXU_INTR_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `spim_ssi_mst_intr` reader - SPIM master interrupt"]
pub struct SPIM_SSI_MST_INTR_R(crate::FieldReader<bool, b... | Rust | 0 |
= sensitivity
elif any(k in name for k in ['up_proj', 'down_proj']): # fc1, fc2, etc. for FFN
P_ffn += weight.numel()
S_ffn += sensitivity
# For the target layer, print S_mha, S_ffn, and their ratio
print(f"\nSensitivity analysis for layer {layer}:")
... | Python | 1 |
'''
Accede al tercer elemento de la tupla que creaste en el ejercicio anterior e imprímelo.
'''
#Crear la tupla de cesta de frutas
cesta_de_frutas = ("manzana", "uvas", "banana", "pera", "piña")
#acceder al tercer elemento de la tupla
tercer_elemento = cesta_de_frutas[2] #el indice del tercer elemento es 2, ya que l... | Python | 1 |
ery) -> Element {
Element::builder("bind", ns::BIND)
.append_all(
bind.resource
.map(|resource| Element::builder("resource", ns::BIND).append(resource)),
)
.build()
}
}
/// The response for resource binding, containing the client’s ful... | Rust | 0 |
#!/usr/bin/python
"""
(gdb) disassemble vulnerable
Dump of assembler code for function vulnerable:
0x1000054c <+0>: stwu r1,-144(r1)
...
0x100005a8 <+92>: lwz r0,4(r11)
0x100005ac <+96>: mtlr r0
0x100005a8 <+100>: lwz r31,-4(r11)
0x100005b4 <+104>: mr r1,r11
0x100005b8 <+108>: blr... | Python | 1 |
``
/// use server::prelude::*;
///
/// fn a() -> Result<()> {
/// bail!("This is an error");
/// }
///
/// fn b() -> Result<()> {
/// bail!(StatusCode::NOT_FOUND, "This is an error");
/// }
///
/// fn c() -> Result<()> {
/// bail!(StatusCode::BAD_REQUEST, "error occurred: {}", 123);
/// }
/// ```
#[macro_ex... | Rust | 0 |
# =============================================================================
# Minet Twitter Tweets CLI Action
# =============================================================================
#
# Logic of the `tw tweets` action.
#
from twitwi import normalize_tweet, normalize_tweets_payload_v2, format_tweet_as_csv_ro... | Python | 1 |
import io
import os
from typing import Tuple
import paramiko
from paramiko import SFTPClient, SFTPFile
import boto3
s3 = boto3.client('s3')
ssh = paramiko.SSHClient()
def get_sftp_client(hostname: str, port: int, username: str, password: str) -> SFTPClient:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy(... | Python | 1 |
#!/usr/bin/env python3
""" Main 4
"""
from api.v1.auth.basic_auth import BasicAuth
a = BasicAuth()
print(a.extract_user_credentials(None))
print(a.extract_user_credentials(89))
print(a.extract_user_credentials("Holberton School"))
print(a.extract_user_credentials("Holberton:School"))
print(a.extract_user_credentials(... | Python | 1 |
def exec8():
soma= 0
for i in range(1, 501):
if i%2 == 0:
soma= soma+i
print(f"O somatório dos números pares de 1 a 500 é: {soma}")
if __name__== '__main__':
exec8() | Python | 1 |
{
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits =
(self.w... | Rust | 0 |
, 1)
};
test_random_shape(xs, rng, |tree| {
check_delete_single(tree, iv);
});
true
}
fn check_delete_single(orig: &mut IntervalTeardownSet<KeyInterval<usize>>, rm: KeyInterval<usize>) -> IntervalTeardownSet<KeyInterval<usize>>
{
let mut tree = orig.cl... | Rust | 0 |
let Some(ffcmp_insn) = maybe_input_insn(ctx, flag_input, Opcode::Ffcmp) {
lower_fcmp_or_ffcmp_to_flags(ctx, ffcmp_insn);
ctx.emit(Inst::CondBr {
taken,
not_taken,
kind,
});
... | Rust | 0 |
from setuptools import setup
setup(
name='pv', #Como invocar a nuestra linea de comandos
version='0.1', #Version
py_modules=['pv'], #Modulo se va a llamar pv
install_requires=[ #Necesitamos como requisito de aplicación el modulo Click
'Click',
],
entry... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
from typing import Union
from mmengine.config import Config, ConfigDict
def get_test_pipeline_cfg(cfg: Union[str, ConfigDict]) -> ConfigDict:
"""Get the test dataset pipeline from entire config.
Args:
cfg (str or :obj:`ConfigDict`): the entire config. ... | Python | 1 |
import pytest
from pyobjus import autoclass, objc_arr
@pytest.mark.parametrize(
"input_array",
[
pytest.param([], id="empty array"),
pytest.param([1, 2, 3], id="non empty array"),
]
)
def test_objc_arr_behaviour(input_array):
NSArray = lambda: autoclass('NSArray')
a1 = NSArray().a... | Python | 1 |
read()` method returns [uca0ctl0::R](uca0ctl0::R) reader structure"]
impl crate::Readable for UCA0CTL0 {}
#[doc = "`write(|w| ..)` method takes [uca0ctl0::W](uca0ctl0::W) writer structure"]
impl crate::Writable for UCA0CTL0 {}
#[doc = "USCI A0 Control Register 0"]
pub mod uca0ctl0;
#[doc = "USCI A0 Baud Rate 0\n\nThis ... | Rust | 0 |
}
Ok(())
}
}
pub struct LineFormatter;
impl ClipFormatter for LineFormatter {
fn print(clips: &Clips, key: Option<char>, unnamed_only: bool) -> Result<(), String> {
if let Some(key) = key {
let clip = clips.get(key, unnamed_only);
// consume the error in raw f... | Rust | 0 |
{}", oper.name, idx_expr);
trace!("{:?} {}", ExprErrorKind::InvalidParamCount, message);
return Err(ExprError {
idx_expr,
kind: ExprErrorKind::InvalidParamCount,
message
});
... | Rust | 0 |
let mut holder = SegmentHolder::default();
let sid1 = holder.add(segment1);
let sid2 = holder.add(segment2);
assert_ne!(sid1, sid2);
let segment3 = build_simple_segment(dir.path(), 4, Distance::Dot).unwrap();
let (_sid3, replaced_segments) = holder.swap(segment3, &[si... | Rust | 0 |
ut_name = os.path.join(a.out_dir, '%s-%s-%d-%d' % (basename(a.pkl1).split('-')[0], basename(a.pkl2).split('-')[0], a.res, a.level))
save_pkl(Net_out, '%s.pkl' % out_name)
rnd = np.random.RandomState(696)
grid_latents = rnd.randn(4, *Gs_out.input_shape[1:])
grid_fakes = Gs_... | Python | 1 |
sort_values()
"""
from sklearn.preprocessing import OrdinalEncoder
encoder = OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=999)
holi_days = pd.Series(
encoder.fit_transform(country_holidays.to_numpy().reshape(-1, 1)).flatten(),
name="HolidayFlag... | Python | 1 |
safe fn StencilFunc(&self, func: GLenum, ref_: GLint, mask: GLuint) {
#[cfg(all(debug_assertions, feature = "debug_trace_calls"))]
{
trace!("calling gl.StencilFunc({:#X}, {:?}, {:?});", func, ref_, mask);
}
let out = call_atomic_ptr_3arg(
"glStencilFunc",
&self.glStencilF... | Rust | 0 |
from django_filters import rest_framework as django_filters # pip install django-filter
from .models import Book, FlashSale
class BookFilter(django_filters.FilterSet):
min_price = django_filters.NumberFilter(field_name="price", lookup_expr='gte')
max_price = django_filters.NumberFilter(field_name="price", loo... | Python | 1 |
()](crate::interface::StakingService::stake)
/// - depositing and staking NEAR funds is performed as atomic batched transaction, i.e., if
/// the batched transaction fails for any reason, e.g., exceeded prepaid gas, then no funds
/// are transferred
Staking,
/// indicates the batch funds have be... | Rust | 0 |
n>
}
}
fn main() {
yew::start_app::<App>();
}
<reponame>PsiACE/arrow2
/// Example demonstrating how to write to parquet in parallel.
use std::sync::Arc;
use rayon::prelude::*;
use arrow2::{
array::*, datatypes::PhysicalType, error::Result, io::parquet::write::*,
record_batch::RecordBatch,
};
fn para... | Rust | 0 |
let mut multi = 0;
while (*p).divides(*n) {
*n /= *p;
multi += 1;
}
break (*p, multi);
}
})
}
}
}
/// Takes an unsigned integer and returns an iterator to yield all... | Rust | 0 |
c![(Attr::Charset, Value::Utf8)])));
Ok(resp)
}
<gh_stars>0
mod result;
mod unix_timestamp;
pub mod util;
mod weekday;
#[cfg(feature = "std")]
mod std_support;
pub use self::unix_timestamp::UnixTimestamp;
use crate::{
context,
page::{Page, PageKind},
WrappedPostMap, SECRET,
};
use hmac::{Hmac, Mac, N... | Rust | 0 |
});
}
}
fn draw_neighbor_cell(
&self,
ctx: &CanvasRenderingContext2d,
cellule: &Cellule,
neighbor_index: usize,
cellule_x: f64,
cellule_y: f64,
) {
let radius = (BASE_CELLULE_SIZE as f64) / 2.0;
let modifiers = match neighbor_index {
0 => (-1.0, -1.0),
1 =>... | Rust | 0 |
def compute_harmonic_series(n: int) -> float:
'''
takes an integer n and computes and returns
the sum of the harmonic series to n
>>> compute_harmonic_series(4)
2.083333333333333
>>> compute_harmonic_series(-3)
0.0
>>> compute_harmonic_series(1)
1.0
>>> compute_harmonic_series(... | Python | 1 |
# pylint: disable=missing-module-docstring
# pylint: disable=missing-function-docstring
# pylint: disable=use-dict-literal
# pylint: disable=invalid-name
# pylint: disable=import-outside-toplevel
def solution(s: str, word_dict):
# for word in word_dict:
# print(word, s.find(word))
word_dict = set(word... | Python | 1 |
mut a = Compressed::<f64>::zero((3, 3));
a.set((0, 0), 2.0);
a.set((0, 1), -1.0);
a.set((0, 2), 1.0);
a.set((1, 0), 4.0);
a.set((1, 1), 1.0);
a.set((1, 2), -1.0);
a.set((2, 0), 1.0);
a.set((2, 1), 1.0);
a.set((2, 2), 1.0);
println!("Original matrix:");
for i in 0..3 {
... | Rust | 0 |
.variant(DIVM_A::DIVM_3)
}
#[doc = "f(MCLK)/16"]
#[inline(always)]
pub fn divm_4(self) -> &'a mut W {
self.variant(DIVM_A::DIVM_4)
}
#[doc = "f(MCLK)/32"]
#[inline(always)]
pub fn divm_5(self) -> &'a mut W {
self.variant(DIVM_A::DIVM_5)
}
#[doc = "f(MCLK)/64"]
... | Rust | 0 |
mestamp};
use timely::progress::nested::product::Product;
use differential_dataflow::collection::{Collection};
use differential_dataflow::lattice::Lattice;
use differential_dataflow::input::{Input, InputSession};
use differential_dataflow::trace::implementations::ord::{OrdValSpine, OrdKeySpine};
use differential_dataf... | Rust | 0 |
"""
デバッグコマンドラインインターフェース
UI階層のダンプやデバッグ機能を提供するCLIツール。
"""
import click
import json
import sys
import logging
from pathlib import Path
from typing import Optional
from src.debug.game_debug_client import GameDebugClient
from src.debug.ui_debug_helper import UIDebugHelper
logger = logging.getLogger(__name__)
@click.gr... | Python | 1 |
from ...attrs import LIKE_NUM
_num_words = set(
"""
zero un une deux trois quatre cinq six sept huit neuf dix
onze douze treize quatorze quinze seize dix-sept dix-huit dix-neuf
vingt trente quarante cinquante soixante soixante-dix septante quatre-vingt huitante quatre-vingt-dix nonante
cent mille mil million milli... | Python | 1 |
rder[order]['W']))
W = ng.expand_dims(W, ax_kernel_D, 0)
W = ng.axes_with_order(W, axes=internal_ax_dict['W'])
# convolution
Y = ng.convolution(params, X, W, axes=internal_ax_dict['Y'])
# cast back to proper format
Y = ng.broadcast(Y, ng.make_axes([ax_N, oD, oH, oW, oC]... | Python | 1 |
ile("_filpreload");
Ok(())
}
//! Tests auto-converted from "sass-spec/spec/libsass-closed-issues/issue_613.hrx"
#[allow(unused)]
fn runner() -> crate::TestRunner {
super::runner()
}
#[test]
fn test() {
assert_eq!(
runner().ok("$var: 1;\n\
\n@mixin test {\
\n $var: 2;\
... | Rust | 0 |
p::new(this).ptr
}
unsafe fn unerase(this: ErasedPtr) -> Self {
Thin {
ptr: this,
marker: PhantomData,
}
}
}
unsafe impl<T: ?Sized> ErasablePtr for &'_ T
where
T: Erasable,
{
fn erase(this: Self) -> ErasedPtr {
T::erase(this.into())
}
unsafe... | Rust | 0 |
.post(record_external))
}
/// Update the clickstream with a single on-site click instance. No-op
/// when compiled in debug mode.
pub async fn record_click(mut req: tide::Request<Database>) -> tide::Result {
if cfg!(not(debug_assertions)) {
async_std::task::spawn(
surf::post(&*CLICK_ENDPOINT)
... | Rust | 0 |
h, Serialize, Deserialize)]
pub struct CoinType(u32);
impl CoinType {
/// Atom (Cosmos) coin type with number 118.
pub const ATOM: CoinType = CoinType(118);
pub fn new(coin_type: u32) -> Self {
Self(coin_type)
}
pub fn num(&self) -> u32 {
self.0
}
}
impl Default for CoinType ... | Rust | 0 |
fn is_defined(&self) -> bool {
self.is_some()
}
}
/// Updates [RenderPipelines] with the latest [ShaderDefs]
pub fn shader_defs_system<T>(mut query: Query<(&T, &mut RenderPipelines)>)
where
T: ShaderDefs + Send + Sync + 'static,
{
for (shader_defs, mut render_pipelines) in query.iter_mut() {
... | Rust | 0 |
_buf(&res_buf);
}
ReadMode::MultipleNToHighest => {
let mut res_buf: [u16; 2] = [0; 2];
adc.read_multiple_channels_n_to_highest(
&mut cmd_buf,
&mut res_buf.iter_mut(),
AN2_CHANNEL,
&mu... | Rust | 0 |
= "model", rename_all = "camelCase")]
pub struct ModelRaw {
pub id: Option<String>,
pub metaid: Option<String>,
pub name: Option<String>,
pub substance_units: Option<UnitSIdRef>,
pub time_units: Option<UnitSIdRef>,
pub extent_units: Option<UnitSIdRef>,
pub volume_units: Option<UnitSIdRef>,
... | Rust | 0 |
high_end_idx - NEW_HIGH_DAYS)
high_data = daily_data.iloc[high_start_idx:high_end_idx]
if yesterday_data['close'] < high_data['close'].max():
continue
# 所有条件都满足,将股票添加到选股结果中
selected_stocks.append(stock_code)
logger... | Python | 1 |
: 0.0,
amount_right: 0.0,
amount_forward: 0.0,
amount_backward: 0.0,
amount_up: 0.0,
amount_down: 0.0,
rotate_horizontal: 0.0,
rotate_vertical: 0.0,
scroll: 0.0,
speed,
sensitivity,
}
}
... | Rust | 0 |
alives);
display!(f, self.krbsrvname);
display!(f, self.options);
display!(f, self.passfile);
display!(f, self.password);
display!(f, self.port);
display!(f, self.replication);
display!(f, self.requirepeer);
display!(f, self.service);
display!(f, s... | Rust | 0 |
import seaborn as sns
import matplotlib.pyplot as plt
class AverageMeter(object):
"# source: https://github.com/HobbitLong/SupContrast/blob/master/util.py"
def __init__(self, name: str, fmt: Optional[str] = ':f'):
self.name = name
self.fmt = fmt
self.reset()
def reset(self):
... | Python | 1 |
std = init_std
self.init_off = init_off
self.nx_node = nx_node
self.num_node = num_node
#normal init A
#A.shape --> (num_filter,num_node,num_node) for example: (8,25,25)
self.A = getattr(self, mode)()
if CoM != None:
self.HA = self.get_hierarchical_gr... | Python | 1 |
, _command_buffer: CommandBuffer) {
}
fn record_ui(&self, _command_buffer: CommandBuffer) {
}
fn update(&mut self, _params: &mut Params, _stats: &Stats) -> ::siege_render::Result<bool> {
Ok(false)
}
fn gpu_update(&mut self) -> ::siege_render::Result<()> {
Ok(())
}
fn ... | Rust | 0 |
put_aliases:
input_memory_spaces_list[input_output_alias[0]] = output_memory_spaces[
input_output_alias[1]
]
input_memory_spaces = tuple(input_memory_spaces_list)
out_nodes = mosaic.lower_module_to_custom_call(
kernel_ctx,
*dynamic_grid_args,
*extra_args,
*args,
... | Python | 1 |
/// The assignment by division operator, `/=`.
DivAssign,
/// The assignment by modulo operator, `%=`.
ModAssign,
}
/// A variable assignment.
#[derive(Debug, PartialEq)]
pub struct Assignment {
/// The identifier being assigned to.
pub ident: Node<Ident>,
/// The declared value.
pub... | Rust | 0 |
return """\
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
width
widthsrc
Sets the source reference on Chart Studio Cloud for
`width`.
"""
def __init__(
self, arg=None, color=None, ... | Python | 1 |
def solution(array, commands):
answer = []
for command in commands:
i = command[0]
j = command[1]
k = command[2]
tmp_array = array[i-1:j]
tmp_array.sort()
answer.append(tmp_array[k-1])
return answer | Python | 1 |
Debug, PartialEq, Eq)]
pub struct Encoding {
recipe: u16,
bits: u16,
}
impl Encoding {
/// Create a new `Encoding` containing `(recipe, bits)`.
pub fn new(recipe: u16, bits: u16) -> Self {
Self { recipe, bits }
}
/// Get the recipe number in this encoding.
pub fn recipe(self) -> us... | Rust | 0 |
Matrix {
Matrix {
cols: self.cols,
rows: self.rows,
data: self.data.iter().map(|x| x - _rhs).collect(),
}
}
}
}
<gh_stars>10-100
// Copyright 2019-2021 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam is free software: you... | Rust | 0 |
type: SigType, data: &[u8]) -> Result<Self, Error> {
match sig_type {
SigType::DsaSha1 => Ok(Signature::DsaSha1(dsa::DsaSignature::from_bytes(data)?)),
SigType::EcdsaSha256P256 => Ok(Signature::EcdsaSha256P256(
FixedSignature::from_bytes(data).map_err(|_| Error::InvalidSi... | Rust | 0 |
.clone(), data_b.clone()]);
let metainfo_bytes = MetainfoBuilder::new()
.set_piece_length(PieceLength::Custom(1024))
.build(1, files_accessor, |_| ()).unwrap();
let metainfo_file = Metainfo::from_bytes(metainfo_bytes).unwrap();
// Spin up a disk manager and add our created torrent to it
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.