text string | label_name string | labels int64 |
|---|---|---|
{
let mut recipe = Vec::new();
recipe.push(ingredients[0].mult(i));
recipe.push(ingredients[1].mult(j));
recipe.push(ingredients[2].mult(k));
recipe.push(ingredients[3].mult(l));
... | Rust | 0 |
ordlist.len() > 1 && i == ROUND_NUM {
debug!("\n{} candidate words left.", wordlist.len());
debug!("\nGame over.");
break;
}
}
None
}
fn word_iter<'a>(
word_opt: Option<&'a Word>,
wordlist: &'a Wordlist,
) -> impl Iterator<Item = &'a Word> {
let iter = i... | Rust | 0 |
pub fn download<U>(&mut self, url: U) -> HttpClientResult<PathHandle>
where
U: IntoUrl + Display,
{
let file_path = self
.download_directory
.join(format!("{}.temp", self.file_seq_no));
info!("Downloading file {} to {}", url, file_path.display());
let mu... | Rust | 0 |
let key = self
.loaded
.iter()
.find(|(k, _)| {
k.to_str()
.unwrap()
.contains(path.as_ref().to_str().unwrap())
})
.ok_or(IOError::NotLoaded(
... | Rust | 0 |
}
}
/// `BitSetNot` takes a [`BitSetLike`] item, and produced an inverted virtual set.
/// Note: the implementation is sub-optimal because layers 1-3 are not active.
///
/// [`BitSetLike`]: ../trait.BitSetLike.html
#[derive(Debug, Clone)]
pub struct BitSetNot<A: BitSetLike>(pub A);
impl<A: BitSetLike> BitSetLike for ... | Rust | 0 |
_EStreamP2PScopeFriends,
EStreamP2PScope::k_EStreamP2PScopeEveryone,
];
values
}
fn enum_descriptor_static() -> &'static ::protobuf::reflect::EnumDescriptor {
static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::EnumDescriptor> = ::protobuf::rt::LazyV2::INIT;
... | Rust | 0 |
lbs_weights=self.weights,
dtype=self.dtype)
Jtr = joints + trans.unsqueeze(dim=1)
verts = verts + trans.unsqueeze(dim=1)
v_posed = v_posed ... | Python | 1 |
t;
type Signature = Signature;
type EncryptedSignature = Signature;
fn new_private_key() -> Self::PrivateKey {
Scalar::random(&mut OsRng)
}
fn to_public_key(key: &Self::PrivateKey) -> Self::PublicKey {
key * &ED25519_BASEPOINT_TABLE
}
fn bytes_to_private_key(bytes: [u8; 32]) -> anyhow::Result<Se... | Rust | 0 |
::Test
} else {
Category::Custom
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Priority {
Verbose,
Debug,
Info,
Warn,
Error,
Critical,
}
impl Priority {
fn from_ll(value: sys::SDL_LogPriority) -> Priority {
use crate::sys::SDL_Log... | Rust | 0 |
nodes.get_mut(*s) {
let mut lnext = treenode.level.clone();
lnext.push(d == 1);
d -= 1;
child.level = lnext;
}
}
}
}
fn make_tree_by_reverse_depth_first<I, F>(items: &[I], is_parent_of: F) -> Vec<TreeNode>
where
F: Fn(&I, &I) -> bool,
{
let mut current: Option<usize> = ... | Rust | 0 |
use_opcode::FUSE_REMOVEMAPPING),
#[cfg(target_os = "macos")]
61 => Ok(fuse_opcode::FUSE_SETVOLNAME),
#[cfg(target_os = "macos")]
62 => Ok(fuse_opcode::FUSE_GETXTIMES),
#[cfg(target_os = "macos")]
63 => Ok(fuse_opcode::FUSE_EXCHANGE),
/... | Rust | 0 |
refix(autogen_context),
"opts": (
", " + (", ".join("%s=%s" % (k, v) for k, v in opts))
if opts
else ""
),
"sqltext": _render_potential_expr(
constraint.sqltext, autogen_context, wrap_in_element=False
),
}
@renderers.dispatch_for(ops.... | Python | 1 |
from autor import Autor
from libro import Libro
def biblioteca ():
# Instanciar autores
autor1 = Autor("Gabriel García Márquez", 1927)
autor2 = Autor("J.K. Rowling", 1965)
autor3 = Autor("George Orwell", 1903)
# Instanciar libros
libro1 = Libro("Cien años de soledad", autor1, 1967)
... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. 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 requir... | Python | 1 |
panic::set_hook(Box::new(|info| {
// Invoke the default handler, which prints the actual panic message and
// optionally a backtrace.
(*DEFAULT_HOOK)(info);
eprintln!();
// Print the current function if available
CURRENT_CODEGEN_ITEM.with... | Rust | 0 |
import pytest
from PyQt6.QtCore import Qt
from pyhamlogger.ui.main_window import MainWindow
@pytest.fixture
def main_window(qtbot):
"""Fixture to create the main window."""
window = MainWindow()
qtbot.addWidget(window)
return window
def test_initial_ui_state(main_window: MainWindow):
"""Test th... | Python | 1 |
platform = line[32:64].lstrip()
if is_sat(platform):
continue
if platform not in data:
data[platform] = []
obs = line[65:].split()[2]
back = line[65:].split()[3]
data[platform].append(f"{network}:... | Python | 1 |
__init__(self, completions: Completions) -> None:
self._completions = completions
self.create = _legacy_response.to_raw_response_wrapper(
completions.create,
)
class AsyncCompletionsWithRawResponse:
def __init__(self, completions: AsyncCompletions) -> None:
self._compl... | Python | 1 |
ust#12223.
let output = tokenize(input.clone(), opts.clone());
if output != expect {
fail!("\ninput: {}\ngot: {}\nexpected: {}",
input, output, expect);
}
}
}),
}
}
fn mk_tests(tests: &mut Vec<TestDescAn... | Rust | 0 |
#[no_mangle]
pub extern "C" fn _start() -> ! {
unsafe {
caps::init();
flatrt_allocator::init(HEAP_START, caps::RPT);
flatrt_capalloc::init(caps::CAPSET, DYN_CAP_START);
// shmem_create endpoint.
IPC_HANDLER.try_lock().unwrap().make_ipc_endpoint(
spec::TaskEndpo... | Rust | 0 |
make_decreasing_gas_price_strategy(GasPrice(2000000000))
)
contract_proxy, _ = deploy_rpc_test_contract(deploy_client, "RpcTest")
address = contract_proxy.address
assert len(deploy_client.web3.eth.get_code(address)) > 0
client_invalid_nonce = JSONRPCClient(web3=deploy_client.web3, privkey=depl... | Python | 1 |
#!/usr/bin/env python3
# <xbar.title>Leetcode Reminder</xbar.title>
# <xbar.version>v1.1.0</xbar.version>
# <xbar.author>zihengjackchen</xbar.author>
# <xbar.author.github>zihengjackchen</xbar.author.github>
# <xbar.desc>Leetcode reminder and status in your memu bar!</xbar.desc>
# <xbar.dependencies>python3</xbar.depe... | Python | 1 |
(unsafe { &*SciterAPI() })
}
}
lazy_static! {
pub static ref API: &'static ISciterAPI =
try_load_library().expect("Failed to load Sciter library");
pub static ref GAPI: &'static SciterGraphicsAPI = unsafe { &*(API.GetSciterGraphicsAPI)() };
pub static ref RAPI: &'static SciterRequestAPI = unsaf... | Rust | 0 |
nfig: dict[str, Any] = {
"workers": config["workers"],
"tools": config["tools"],
"client": config["client"],
}
convos: list[list[dict[str, Any]]] = generate_labeled_convos(
intent_paths, summary, model_api, model_params, client, env_config
)
return convos
def main() -> ... | Python | 1 |
= 1
if AUDIO_SAMPLE_RATE_HZ == 48000:
downsample_factor = 3
# Most microphones support this
# Because the model expects 16KHz audio, we downsample 3 fold
recorder = audio_recorder.AudioRecorder(
AUDIO_SAMPLE_RATE_HZ,
downsample_factor=downsample_factor,
device_index=audio_device_index)
... | Python | 1 |
from flask import Flask
from ..server.routes.routes import phrase_route_bp, word_route_bp
app = Flask(__name__)
app.register_blueprint(phrase_route_bp)
app.register_blueprint(word_route_bp) | Python | 1 |
ose(A, PL @ U)
True
"""
a1 = np.asarray_chkfinite(a) if check_finite else np.asarray(a)
if a1.ndim < 2:
raise ValueError('The input array must be at least two-dimensional.')
# Also check if dtype is LAPACK compatible
if a1.dtype.char not in 'fdFD':
dtype_char = lapack_cast_dict... | Python | 1 |
_bindgen)]
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, Copy, Hash, Ord, PartialOrd)]
pub enum Color {
#[serde(rename = "b")]
Black,
#[serde(rename = "r")]
Red,
}
impl From<Pattern> for Color {
fn from(c: Pattern) -> Self {
match c {
Pattern::Spade | Pattern::Cl... | Rust | 0 |
}
}
}
/// Custom expansion for conditional trap instructions.
/// TODO: Add CFG support to the Rust DSL patterns so we won't have to do this.
fn expand_cond_trap(
inst: ir::Inst,
func: &mut ir::Function,
cfg: &mut ControlFlowGraph,
_isa: &dyn TargetIsa,
) {
// Parse the instruction.
l... | Rust | 0 |
with open("F:\\python practice\\Assignment\\stocks.csv","r") as f, open("F:\\python practice\\Assignment\\ouput.csv","w") as out:
out.write("Company Name, PE Ratio, PB Ratio\n")
next(f)
for line in f:
names= line.split(',')
stocks= names[0]
price= float(names[1])
ear= flo... | Python | 1 |
::read_directory;
use crate::writer::write_classes;
macro_rules! time_it {
($expr:expr) => {{
let now = ::std::time::Instant::now();
$expr;
(::std::time::Instant::now() - now).as_millis()
}};
}
fn main() {
println!("Total Time: {}ms", time_it!(main_()));
}
fn main_() {
let mut... | Rust | 0 |
{
bytes = &bytes[1..];
f.write_str("\\n")?;
},
b'\r' => {
bytes = &bytes[1..];
f.write_str("\\r")?;
},
b'\t' => {
bytes = &bytes[1..];
f.write_str("\\t")?;
},
b'"' => {
bytes = &bytes[1..];
f.write_str("\\\"")?;
},
b'\\' => {
bytes = &bytes[1... | Rust | 0 |
}
}
Self {
cache: cache.into_boxed_slice(),
}
}
}
impl<R> SchoenhageTriadicDomain<R>
where
R: 'static + Ring + RingInvertible + Clone + Send + Sync,
{
pub fn reduce(&mut self, level: usize) {
let n = pow(3, level);
self.level = LevelData::Lev... | Rust | 0 |
iter().map(|b| b.rotate180()).collect();
let whites = PieceBitBoards {
pawns: pawns,
knights: knights,
bishops: bishops,
rooks: rooks,
queens: queens,
kings: kings,
};
let blacks = PieceBitBoards {
pawns: black_... | Rust | 0 |
cash_primitives::merkle_tree::IncrementalWitness;
use zcash_primitives::primitives::PaymentAddress;
use zcash_primitives::primitives::Rseed;
use zcash_primitives::transaction::components::{Amount, OutPoint};
use zx_bip44::BIP44Path;
use ledger_zcash::{APDUTransport, ZcashApp, PK_LEN_SAPLING, PK_LEN... | Rust | 0 |
#!/usr/bin/env python3
# Canary-Qwen2.5b: https://huggingface.co/nvidia/canary-qwen-2.5b
# Nemo requirements:
# "git+https://github.com/NVIDIA/NeMo.git@6294bc7708ce67522b92f5e9b6917ea0b2e23429#egg=nemo_toolkit[asr]"
# tqdm
# soundfile
# librosa
# huggingface_hub>=0.24
# IPython # Workaround for https://github.com/N... | Python | 1 |
ogging.info("Saved checkpoint to ckpt-last.pth ...")
ckpt = {
"cfg": cfg,
"epoch_index": epoch_idx,
"gancraft_g": gancraft_g.state_dict(),
"gancraft_d": gancraft_d.state_dict(),
}
if cfg.TRAIN.GANCRAFT.EMA_ENABLED:
... | Python | 1 |
"workspaceId": pytest.workspace.get("id"),
"sessionId": session_id,
"modelKwargs": {"temperature": 0},
},
}
client.send_query(json.dumps(request))
found = False
retries = 0
while not found and retries < 30:
time.sleep(1)
retries += 1
session ... | Python | 1 |
from odoo import fields, models
class HrDepartment(models.Model):
_inherit = 'hr.department'
def _get_responsibility_center_id_domain(self):
return "[('plan_id', 'child_of', %s), '|', ('company_id', '=', False), ('company_id', '=', company_id)]" \
% self.env.ref('analytic_responsibility_c... | Python | 1 |
rename = "FK")]
FalklandIslands,
/// FAROE ISLANDS
#[serde(rename = "FO")]
FaroeIslands,
/// FIJI
#[serde(rename = "FJ")]
Fiji,
/// FINLAND
#[serde(rename = "FI")]
Finland,
/// FRANCE
#[serde(rename = "FR")]
France,
/// FRENCH GUIANA
#[serde(rename = "GF")]
FrenchGuiana,
/// FRENCH POLYNESIA
#[serde(r... | Rust | 0 |
} // fn
} // impl<filename>tests/mcp300x_test.rs
use simple_sensors::mcp300x;
mod fake_hal;
use fake_hal::spi as fake_spi;
macro_rules! test_synchronous_read_success {
($name:ident, $read_fn:expr, $request:expr) => {
#[test]
fn $name() -> Result<(), mcp300x::Error<fake_spi::SpiError>> {
... | Rust | 0 |
Si el slice tiene menos de `index + 1` elementos retorna un tremendo `None`
// recordemos que no podemos indexar los elementos de una coleccion con `u32` o `ixx` el unico
// type que esta permitido para indexar es `usize`(para que funcione en todas las plataformas!!!)
//
// `slice.first_mut()`, `slice.last_mut()` y `s... | Rust | 0 |
ont = pygame.font.Font("chinesefont.ttf", 24)
description_text = description_font.render(difficulty_descriptions[i*2], True, description_color)
description_rect = description_text.get_rect(midleft=(WIDTH*4 // 10, y_offset))
screen.blit(description_text, description_rect)
description_text... | Python | 1 |
port.module_path().to_string()).into());
}
Ok((
import.module_path().clone(),
output_directory.join(
&FilePath::new(vec![
OBJECT_DIRECTORY,
&module_id_calculator::calculate(&source_file),
])
... | Rust | 0 |
def continue_fibonacci_sequence(sequence, n):
for i in range(n):
next_element = sequence[-1] + sequence[-2]
sequence += [next_element]
sequence = [1, 1]
continue_fibonacci_sequence(sequence, 1)
print(*sequence) | Python | 1 |
5763113464139,
-0.35390281459663013491031287081289167626,
0.35390281459663013491031287081289167626,
-0.35390281459663013491031287081289167626,
0.35390281459663013491031287081289167626,
-0.94124485721060326391115015763113464139,
0.94124485721060326391115015763113464139,
... | Rust | 0 |
principal_data: unsafe { *self.principal },
}
}
}
#[derive(Debug)]
pub struct Krb5PrincipalData<'a> {
pub(crate) context: &'a Krb5Context,
pub(crate) principal_data: krb5_principal_data,
}
impl<'a> Krb5PrincipalData<'a> {
pub fn realm(&self) -> Result<String, Krb5Error> {
let realm... | Rust | 0 |
let class = value.count_ones() as u8;
let (_, code) = encode(value, class);
(0..64).all(|i| {
let computed = rank(code, class, i);
let expected = (value & ((1 << i) - 1)).count_ones() as u64;
computed == expected
})
}
#[quickcheck]
fn qc_s... | Rust | 0 |
import numpy as np
from typing import Literal
from dataclasses import dataclass
from mlffbrew.typing import npstr, npf64, Box, Atoms, Coords, Energy, Stress, Virial, Force
STATE_KEYS = ["coords", "atoms", "energy", "stress", "virial", "force", "box"]
@dataclass(slots=True)
class State:
coords: Coords = None
... | Python | 1 |
},
SkipAuthRoute {
path: "/api/tags",
method: Method::GET,
},
SkipAuthRoute {
path: "/api/users",
method: Method::POST,
},
SkipAuthRoute {
path: "/api/users/login",
method: Method::POST,
},
SkipAuthRoute {
path: "/api/articles",
... | Rust | 0 |
_min:f64, t_max:f64, rec:&mut HitRecord)->bool{
let oc = r.position.clone() - self.center.clone();
let dir=r.direction.clone();
let a = dir.squared_length();
let half_b = oc.clone()*dir;
let c = oc.clone().squared_length() - self.radius * self.radius ;
let discriminant = half_b * half_b - ... | Rust | 0 |
import pytest
from autorag.nodes.passagereranker.koreranker import KoReranker
from tests.autorag.nodes.passagereranker.test_passage_reranker_base import (
base_reranker_test,
base_reranker_node_test,
ko_queries_example,
ko_contents_example,
ids_example,
project_dir,
ko_previous_result,
)
from tests.delete_tests... | Python | 1 |
from .common import moulti_test
assert moulti_test
COMMAND = ['maximize.bash']
def test_maximize_small_step(moulti_test):
# Maximize the first step:
assert moulti_test(command=COMMAND, press=('tab', 'tab', 'f'))
def test_unmaximize_small_step(moulti_test):
# Maximize then unmaximize the first step:
assert moulti... | Python | 1 |
from pathlib import Path
with open(Path(__file__).parent / "input.txt", "r") as file:
block1, _ = file.read().split("\n\n")
workflows = {}
for line in block1.splitlines():
name, rest = line[:-1].split("{")
rules = rest.split(",")
workflows[name] = ([], rules.pop())
for rule in rules:
comp... | Python | 1 |
pos: vec![Vector::zero(); SIZE],
};
$group.bench_function($name, |b| {
b.iter(|| {
for ((position, acceleration), velocity) in
data.pos.iter_mut().zip(&data.acc).zip(&mut data.vel)
{
*velocity += *accelerati... | Rust | 0 |
("\r\n", "\n")),
// Deviate from grammar by pulling mll_quotes into here so we can handle the confusion with
// it and the closing delim
choice((
attempt((
bytes(b"''"), range(ML_LITERAL_STRING_DELIM)
)).map(|_| Some("''")),
attempt((
... | Rust | 0 |
w(c0, c1)
}
#[inline]
fn get_constant(&self) -> QuadExtField<P> {
self.get_value().unwrap()
}
}
extern crate clap;
extern crate failure;
extern crate polonius_engine;
extern crate rustc_hash;
extern crate structopt;
mod dump;
mod facts;
mod intern;
mod program;
mod tab_delim;
mod test;
mod tes... | Rust | 0 |
import tensorflow as tf
devices = tf.config.experimental.list_physical_devices('GPU')
tf.keras.utils.set_random_seed(1)
tf.config.experimental.enable_op_determinism()
import tf.runner.runner_bnn_weed_map
import tf.runner.runner_bnn_weed_map_random
import tf.runner.runner_bnn_weed_map_sp_active_learn
import tf.runner... | Python | 1 |
"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00..0x2000 - Unspecified"]
pub set: [SET; 256],
}
#[doc = r"Register block"]
#[repr(C)]
pub struct SET {
#[doc = "0x00..0x20 - Unspecified"]
pub way: [self::set::WAY; 2],
}
#[doc = r"Register block"]
#[doc = "Unspecified"]
pub mod set;
m... | Rust | 0 |
eed_state_chunk(hash, &chunk);
}
for hash in manifest.block_hashes {
let chunk = service.chunk(hash).unwrap();
service.feed_block_chunk(hash, &chunk);
}
assert_eq!(service.status(), RestorationStatus::Inactive);
for x in 0..NUM_BLOCKS {
let block1 = client.block(BlockId::Number(x as u64)).unwrap();
let ... | Rust | 0 |
import streamlit as st
import torch
from torchvision import models, transforms
from torchvision.models import ResNet50_Weights
from PIL import Image
import pickle
import pandas as pd
import os
# ==== CONFIG ====
MODEL_PATH = "models/best_artist_classifier_cnn.pth"
ENCODER_PATH = "models/label_encoder.pkl"
ARTIST_CSV_P... | Python | 1 |
width: None,
height: Some(42),
aspect_ratio: None,
frame_rate: Some(30.0),
facing_mode: None,
resize_mode: Some(ResizeMode::CropAndScale),
}
);
}
#[test]
fn debug() {
let subject = Video {
... | Rust | 0 |
trait Deserializer<'de> {
type Error;
}
pub trait Serialize {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer;
}
pub trait Deserialize<'de>: Sized {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>;
}
impl... | Rust | 0 |
# 导入库函数,包括os、tf等等
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '6,7'
import tensorflow as tf
import numpy as np
import glob
import scipy.io as sio
tf.config.run_functions_eagerly(True)
# Using zero-padding to support arbitrary single-lead.
# 采用zero-padding,使得其支持任意单导联
def paddingecg(ecg1,idx=0):
l_index = np.ara... | Python | 1 |
(exist_ok=True)
# views_dir = save_dir_.joinpath('views')
views_dir = save_dir_
views_dir.mkdir(exist_ok=True)
Sr_SAI_y = Sr_SAI_y.to("cpu")
Sr_SAI_ycbcr = torch.cat((Sr_SAI_y, Sr_SAI_cbcr), dim=1)
Sr_SAI_rgb = (
ycbcr2rgb(Sr_SAI_yc... | Python | 1 |
pub const SORT_INVARIANT_MATH: u32 = 1u32;
#[doc = "*Required features: 'Win32_System_SystemServices'*"]
pub const SORT_JAPANESE_RADICALSTROKE: u32 = 4u32;
#[doc = "*Required features: 'Win32_System_SystemServices'*"]
pub const SORT_JAPANESE_UNICODE: u32 = 1u32;
#[doc = "*Required features: 'Win32_System_SystemService... | Rust | 0 |
}
#[test]
fn test_example_1_4() {
assert_eq!(
solve_1(
r"#################
#i.G..c...e..H.p#
########.########
#j.A..b...f..D.o#
########@########
#k.E..a...g..B.n#
########.########
#l.F..d...h..C.m#
#################"
),
(
136,
... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
"""Module providing a K Nearest Neighbour Regression model with appropriate functions"""
class KNearestNeighbors():
"""Class representing a KNN regression model"""
def __init__(self, n = 3):
self.n = n
def fit(self, X_train, y_train):
"""... | Python | 1 |
import cv2
import pytest
from genalog.generation.content import CompositeContent, ContentType
from genalog.generation.document import DocumentGenerator
TEMPLATE_PATH = "tests/e2e/templates"
TEST_OUT_FOLDER = "test_out/"
SAMPLE_TXT = "foo"
CONTENT = CompositeContent([SAMPLE_TXT], [ContentType.PARAGRAPH])
@pytest.fix... | Python | 1 |
"test_oneof"
);
assert!(!dynamic.has_field_by_name("oneof_field_1"));
assert!(!dynamic.has_field_by_name("oneof_field_2"));
dynamic.set_field_by_name("oneof_field_1", Value::String("".to_owned()));
assert!(dynamic.has_field_by_name("oneof_field_1"));
assert!(!dynamic.has_field_by_name("o... | Rust | 0 |
import argparse
import numpy as np
def compute_split_parts(num_samples, num_parts):
part_samples = num_samples // num_parts
remain_samples = num_samples % num_parts
if part_samples == 0:
return [num_samples]
if remain_samples == 0:
return [part_samples] * num_parts
else:
r... | Python | 1 |
rule identifier() -> String
= s:$(!keyword() (['a'..='z'|'A'..='Z'] ['a'..='z'|'A'..='Z'|'0'..='9'|'_']*
/ ['_']+ ['a'..='z'|'A'..='Z'|'0'..='9'] ['a'..='z'|'A'..='Z'|'0'..='9'|'_']*))
{
s.into()
}
rule keyword() -> ()
= (("crate" / "super" / "self" ... | Rust | 0 |
#Embedded file name: /Users/versonator/Jenkins/live/output/mac_64_static/Release/python-bundle/MIDI Remote Scripts/UC33e/consts.py
""" The following consts should be substituted with the Sys Ex messages for requesting
a controller's ID response and that response to allow for automatic lookup"""
ID_REQUEST = 0
ID_RESP =... | Python | 1 |
ytes();
assert_eq!(p1_public_comshares, PublicCommitmentShareList::from_bytes(&bytes).unwrap());
let bytes = p1_partial.to_bytes();
assert_eq!(p1_partial, PartialThresholdSignature::from_bytes(bytes).unwrap());
// Continue signature
aggregator.include_partial_signature(p1_part... | Rust | 0 |
numbering of outgoing
/// edges.
pub fn vertex_degree(&self, vid: VertexIndex) -> usize {
self.adjacent_half_edges_to_vertex(vid).count()
}
/// Returns the number of sides (edges) of the specified face.
pub fn face_sides(&self, fid: FaceIndex) -> usize {
self.adjacent_half_edges_to... | Rust | 0 |
f l.starts_with("fold") {
break;
}
let mut iter = l.split(",").map(|v| i32::from_str(v).unwrap());
map.insert((iter.next().unwrap(), iter.next().unwrap()), 1);
}
(
map,
input
.trim()
.lines()
.filter(|v| v.starts_with("fold"))
.map(|v| {
let v = v.replace("fold along ", "");
let mut ... | Rust | 0 |
with open("sample.txt",'w') as file:
file.write("hello dost\n")
file.close() | Python | 1 |
name(val: i32) -> Option<String> {
unsafe {
from_c_string(raw::pcap_tstamp_type_val_to_name(val))
}
}
pub fn pcap_tstamp_type_val_to_description(val: i32) -> Option<String> {
unsafe {
from_c_string(raw::pcap_tstamp_type_val_to_description(val))
}
}
pub fn pcap_open_live(
device: &... | Rust | 0 |
fn new(action_id: u64) -> MIDGenerator {
// In order to speed up tests, we will generate the first block lazily.
MIDGenerator {
action_id,
next_alloc: 0,
curr_index: MESSAGE_ID_PREALLOC_LEN,
message_ids: [0u64; MESSAGE_ID_PREALLOC_LEN],
}
}
... | Rust | 0 |
import ast
import os
import re
import ipdb
from lmms_eval.tasks.ocrbench_v2.vqa_metric import vqa_evaluation
def calculate_iou(box1, box2):
try:
box1 = [int(coordinate) for coordinate in box1]
box2 = [int(coordinate) for coordinate in box2]
except:
return 0
x1_inter = max(box1[0... | Python | 1 |
from rest_framework import status
from rest_framework.exceptions import APIException
class LabelValidationError(APIException):
status_code = status.HTTP_400_BAD_REQUEST
default_detail = "You cannot create a label with same name or shortcut key."
| Python | 1 |
# Copyright (c) 2022-2024, NVIDIA CORPORATION.
import geopandas as gpd
import numpy as np
import pandas as pd
import cuspatial
def test_sort_index_series(gs):
gs.index = np.random.permutation(len(gs))
cugs = cuspatial.from_geopandas(gs)
expected = gs.sort_index()
got = cugs.sort_index().to_pandas()
... | Python | 1 |
) -> Self {
self.disable_web_page_preview = Some(disable_web_page_preview);
self
}
/// Sends the message silently
///
/// Users will receive a notification with no sound
pub fn disable_notification(mut self, disable_notification: bool) -> Self {
self.disable_notification = S... | Rust | 0 |
.map(|(i, ())| {
let i_u8 = i as u8;
Radio::new(
i_u8,
i_u8.to_string(),
Some(*aktuelle_geschwindigkeit),
geschwindig... | Rust | 0 |
"""
文件名: Code/Chapter06/C05_GN/gn_compute.py
创建时间: 2023/10/8 8:08 下午
作 者: @空字符
公众号: @月来客栈
知 乎: @月来客栈 https://www.zhihu.com/people/the_lastest
"""
import torch
import torch.nn as nn
if __name__ == '__main__':
x = torch.tensor([0, 2, 0, 1, 0, 0, 2, 0, 1, 1, 2, 1, 2, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1,
... | Python | 1 |
Id},
prelude::*,
utils::MessageBuilder,
};
use crate::{
discord::{
channel_groups::{get_group, in_submission_channel, ChannelGroup, ChannelType},
servers::add_spoiler_role,
submissions::{build_leaderboard, process_submission, Submission},
},
games::{get_maybe_active_race, As... | Rust | 0 |
N, GRS80_SEMI_MAJOR, GRS80_SEMI_MINOR)
}
/// Convert OSGB36 coordinates to Lon, Lat using OSTN15 data
#[allow(non_snake_case)]
pub fn convert_osgb36_to_ll(E: f64, N: f64) -> Result<(f64, f64), ()> {
// Apply reverse OSTN15 adustments
let epsilon = 0.009;
let (mut dx, mut dy, _) = ostn15_shifts(E, N)?;
... | Rust | 0 |
# Create a program that reads the name of a person and tells whether it has
# "Silva" in it.
name = str(input('Tell me your name: ')).strip()
print(f"Does your name have Silva? {('silva' in name.lower())}")
| Python | 1 |
class Solution:
def checkEqualTree(self, root: Optional[TreeNode]) -> bool:
if not root:
return False
seen = set()
def dfs(root: Optional[TreeNode]) -> int:
if not root:
return 0
summ = root.val + dfs(root.left) + dfs(root.right)
seen.add(summ)
return summ
sum... | Python | 1 |
101)
Fx = femm.mo_blockintegral(18) #-- 18 x (or r) part of steady-state weighted stress tensor force
Fy = femm.mo_blockintegral(19) #--19 y (or z) part of steady-state weighted stress tensor force
torque = femm.mo_blockintegral(22) #-- 22 = Steady-state weighted stress tensor torque... | Python | 1 |
# -*- coding: utf-8 -*-
# ____________
# ___/ | \_____________ _ _ ___
# / ___/ | _ __ _ _| | ___ __ _ __| | \
# / \___/ ______/ | '_ \ || | |__/ _ \/ _` / _` | \
# \ ◯ | | .__/\_, |____\___/\__,_\__,_| /
# \_______\ /_______|_| |__/... | Python | 1 |
if iface not in addrs:
addrs[iface] = []
for config in configs:
if config["addr"] in addresses:
addrs[iface].append(config['addr'])
g_slave = slave(addresses=addrs)
elif mode == 'getifaddrs':
... | Python | 1 |
.0.1",
//Self::IpV6 => "::1",
}
}
}
impl fmt::Display for MerchantServices {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Note: this hard-codes the default port.
let ipaddr = match self {
Self::IpV4 => self.to_str().to_string(),
//Self::I... | Rust | 0 |
(logits).scatter(1, top_indices, probs)
topk_map = torch.zeros_like(logits).int().scatter(1, top_indices, 1).bool()
tokens_per_expert = topk_map.sum(dim=0)
if capacity_factor is None:
# TopK without capacity
return topk_masked_gates, topk_map, tokens_per_expert
else:
# TopK with... | Python | 1 |
# -*- coding: utf-8 -*-
# Reference: https://en.wikipedia.org/wiki/Hurst_exponent
# python 3.6.2 AMD64
# 2018/4/19
# Calculate Hurst exponent based on Rescaled range (R/S) analysis
# How to use (example):
# import Hurst
# ts = list(range(50))
# hurst = Hurst.hurst(ts)
# Tip: ts has to be object list(n_samples,) or np.... | Python | 1 |
# scripts/audit_append.py
import json
import csv
import sys
from pathlib import Path
from urllib.parse import urlparse
def is_fr_domain(d: str) -> bool:
if not d:
return False
if d.endswith(".gouv.fr"):
return True
return d in {"data.gouv.fr", "insee.fr"} # ancrages minimaux
def domain(ur... | Python | 1 |
return find_last_in_range(view, term, max(hi_line.a, start), min(hi_line.b, end), flags)
# TODO: Test me.
class BufferSearchBase(sublime_plugin.TextCommand):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def calculate_flags(self):
# TODO: Implement smartca... | Python | 1 |
static Target> {
GLOBAL_REGISTRY.lock().unwrap().targets.iter().map(|&t| t).find(|target| {
target.name() == name
}).clone()
}
/// Keeps track of the currently loaded targets.
struct Registry
{
targets: Vec<&'static Target>,
}
impl Registry
{
pub fn new() -> Self {
Registry {
... | Rust | 0 |
n the run starting with k=max_k, at k=k
// the full reduction achieved a reduction in `k` of `x`.
full_param_indep_reduction: HashMap<usize, HashMap<FloatKey, f32>>,
// param_dep_reduction[max_k][k] = x => in the run starting with k=max_k, at k=k
// the param-dependent reduction achieved a reduction in ... | Rust | 0 |
es},
{"name": "Other resolved issues", "tasks": misc}
]
for c in changelog:
c["tasks"].sort(key=lambda x: x["id"])
# Render the changelog
if args.format == "html":
tmpl = jinja2.Template(html_template)
elif args.format == "phriction":
tmpl = jinja2.Template(phriction_template)
elif args.format == "rst"... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.