text string | label_name string | labels int64 |
|---|---|---|
impl fmt::Display for ServerId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
// === impl NoClientTls ===
impl fmt::Display for NoClientTls {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Disabled => write!(f, "dis... | Rust | 0 |
import unittest
from ....content import choose_tool_progression
from ....options import ToolProgression, SkillProgression
from ....strings.tool_names import Tool
class TestToolDistribution(unittest.TestCase):
def test_given_vanilla_tool_progression_when_create_feature_then_only_one_scythe_is_randomized(self):
... | Python | 1 |
= qp(typ, "<<A as B> as Option<T>>");
assert_extent!(p, (0, 23))
}
#[test]
fn struct_basic() {
let p = qp(p_struct, "struct S { field: TheType, other: OtherType }");
assert_extent!(p, (0, 45))
}
#[test]
fn struct_with_generic_fields() {
let p = qp(p_struct, "st... | Rust | 0 |
import pytest
from src.scheduler import PriorityTaskScheduler
from src.tasks import PriorityTask
from src.mock import (
mock_task_quick,
mock_task_with_computation,
mock_task_with_contrived_error,
mock_task_with_random_sleep_duration,
)
MUST_BE_GREATER_THAN_ZERO = "must be greater than 0"
def test_in... | Python | 1 |
#Desenvolva um programa que leia a altura e o peso de uma pessoa,
#e calcule o índice de massa corporal (IMC) e mostre seu status,
#de acordo com a tabela a baixo:
# IMC abaixo de 18,5: abaixo do peso
# IMC peso 18,5 e 25: peso ideal
# IMC peso 25 até 30: sobre peso
# IMC peso 30 ate 40: obesidade
# IMC acima de 40: o... | Python | 1 |
command(SYSTEMCTL_BIN, &["enable", &self.unit])?;
Ok(())
}
fn enable_and_start(&self) -> Result<()> {
command(
SYSTEMCTL_BIN,
&["enable", &self.unit, "--now", "--no-block"],
)?;
Ok(())
}
fn disable_and_stop(&self) -> Result<()> {
... | Rust | 0 |
# Advent of Code 2024
# Dr Lee A. Christie
#
# GitHub: @leechristie
# Mastodon: @0x1ac@techhub.social
# Website: leechristie.com
import time
from functools import cache
def load_rocks() -> list[int]:
with open('input11.txt') as file:
for line in file:
line = line.strip()
retur... | Python | 1 |
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import pandas as pd
import plotly.express as px
from models.age import Age
age_data = (
pd.DataFrame(Age.fetch_all()).rename(columns={
'region': '地区',
'prop_0_to_14': '0到14岁人口占比',
... | Python | 1 |
from collections import Counter
import re
input_filename = "input.txt"
content = ""
try:
with open(input_filename, "r") as infile:
print(f"Raading from '{input_filename}'...")
content = infile.read()
print(f"Finished reading from '{input_filename}'.")
except FileNotFoundError:
print(... | Python | 1 |
= DeviceInfo(
identifiers={(DOMAIN, paired_sensor_uid)},
manufacturer="Elexa",
model=coordinator.data["codename"],
name=f"Guardian paired sensor {paired_sensor_uid}",
via_device=(DOMAIN, entry.data[CONF_UID]),
)
self._attr_unique_id = f"{paire... | Python | 1 |
}
}
<filename>src/main.rs
use kiss3d::camera::FirstPerson;
use kiss3d::light::Light;
use kiss3d::scene::SceneNode;
use kiss3d::window::Window;
use nalgebra::{Point3, Translation3, Vector3};
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{mpsc, Ar... | Rust | 0 |
or text data. ARNs have the format <code>arn:partition:service:region:account-id:resource-type/resource-id</code>.</p>
pub fn set_data_access_role_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.data_access_role_arn = input;
... | Rust | 0 |
ed_potato);
eat(cooked_potatos);
}
<reponame>DenisKolodin/ws_stream_wasm
#![ feature( async_await, trait_alias )]
wasm_bindgen_test_configure!(run_in_browser);
// What's tested:
//
// Tests send to an echo server which just bounces back all data.
//
// ✔ WsStream::connect: Verify error when connecting to a wrong po... | Rust | 0 |
arg("-b:v")
.arg("0")
// output
.arg(path.as_ref().as_os_str())
.output()?;
if result.status.success() {
Ok(())
} else {
Err(HeadlessError::Ffmpeg(
String::from_utf8(result.stderr).unwrap(),
))
}... | Rust | 0 |
"""SQLite-backed repository implementation for NSD data."""
from __future__ import annotations
from typing import List, Set, Tuple, TypeVar
from sqlalchemy.dialects.sqlite import insert
from sqlalchemy import func
from application.ports.config_port import ConfigPort
from application.ports.logger_port import LoggerP... | Python | 1 |
N1,
/// 30/360 (SIA) (A variant of "30/360" - when Date1 and Date2 are both Feb. 28th or 29th convert them to 30th using the same
/// logic in the conversion of 31st to 30th.)
#[serde(rename = "2")]
N2,
/// 30/360M (Commonly used day count convention for US mortgage backed securities. Feb 28th (or 29th in a leap y... | Rust | 0 |
# Definição do menu de opções
menu = '''
[d] Depositar
[s] Sacar
[e] Extrato
[q] Sair
=>: '''
# Inicialização das variáveis de conta
saldo = 0
limite = 500
extrato = "" # Inicializa uma string vazia para armazenar as transações do extrato
numero_sques = 0
LIMITE_SQUES = 3 # Define o limite de saques diários
# Loop... | Python | 1 |
import warnings
from typing import Iterable, Optional
from spacy.tokens import Doc
from spacy.training import Example
from ...compat import Self
from ...ty import FewshotExample
from .task import TranslationTask
class TranslationExample(FewshotExample[TranslationTask]):
text: str
translation: str
@clas... | Python | 1 |
# iso9362.py - compatibility module for stdnum.bic
#
# Copyright (C) 2017 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your... | Python | 1 |
,103,101,114,0]) [CLSID_DataProtectionManager]);
DEFINE_IID!(IID_IDataProtectionManagerStatics, 3054803828, 37188, 20196, 138, 138, 48, 181, 243, 97, 67, 14);
RT_INTERFACE!{static interface IDataProtectionManagerStatics(IDataProtectionManagerStaticsVtbl): IInspectable [IID_IDataProtectionManagerStatics] {
#[cfg(fea... | Rust | 0 |
=> {
first = NARROW_KANA_KATAKANA_U;
second = NARROW_JIS_SYMBOL_KATAKANA_VOICED_SOUND_MARK;
}
WIDE_KANA_KATAKANA_VA => {
first = NARROW_KANA_KATAKANA_WA;
second = NARROW_JIS_SYMBOL_KATAKANA_VOICED_SOUND_MARK;
}
... | Rust | 0 |
.reset_index()
word_count_by_author = word_count_by_author.rename(columns={'word_count': 'total_word_count'})
# Summarize character count by author
character_count_by_author = df.groupby('author')['character_count'].sum().reset_index()
character_count_by_author = character_count_by_author.rename(columns={'character_co... | Python | 1 |
mages", columns=2, rows=2, height=300)
examples_t2i = gr.Examples(
label="Text to image generation examples. (Tips for designing prompts: Adding description like 'digital art' at the end of the prompt or writing the prompt in more detail can help produce better images!)",
examples=[
... | Python | 1 |
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Render(timestamp) => {
// Render functions are likely to get quite large, so it is good practice to split
// it into it's own function rather than keeping it inline in the... | Rust | 0 |
fn argument_to_assignment(arg: &Expression) -> Result<Assignment> {
fn assign_values(assignment: &mut Assignment, expr1: &Expression, expr2: &Expression, errors: &mut Vec<Error>) {
assignment.value = expr2.clone();
if let Some(identifier) = path_expr_to_identifier(expr1, errors) {
assig... | Rust | 0 |
# -*- coding: UTF-8 -*-
"""
-----------------------------------
@Author : Encore
@Date : 2022/9/5
-----------------------------------
"""
from tqdm import tqdm
import json
import torch
from transformers import BertTokenizerFast
from torch.utils.data.dataset import Dataset
from torch.utils.data.dataloader import DataLo... | Python | 1 |
lot_mapd_time_series(
MAPD().series(ref, pre, condition=ref > 1.0),
"Mockup chlorophyll forecast",
"mapd_mockup_series",
xlim=period,
).clear()
plot_mapd_scene(
MAPD().image(ref, pre, condition=ref > 1.0),
"Mockup chlorophyll forecast",
"mapd_mockup_image"... | Python | 1 |
[2]));
let x4: u32 = (0x7fffffe - (arg1[3]));
let x5: u32 = (0x7fffffe - (arg1[4]));
out1[0] = x1;
out1[1] = x2;
out1[2] = x3;
out1[3] = x4;
out1[4] = x5;
}
/// The function fiat_poly1305_selectznz is a multi-limb conditional select.
/// Postconditions:
/// eval out1 = (if arg1 = 0 then eval arg2 else ... | Rust | 0 |
let cached_endpoints: Vec<&'static str> = vec![
"sp_previews",
"coop_previews",
"points1",
"points2",
"points3",
"points4",
"points5",
"points6",
"points7",
"points8",
"points9",
... | Rust | 0 |
let mut ugly: Vec<i32> = vec![1];
let mut i = 0;
let mut j = 0;
let mut k = 0;
while ugly.len() <= n {
let min = vec![ugly[i] * 2, ugly[j] * 3, ugly[k] * 5]
.into_iter()
.min()
.unwrap();
ugly.push(min);
... | Rust | 0 |
];
let mut windows = args.windows(2);
while let Some(a) = windows.next() {
// Skip the first arg, the "--", which also allows us to filter 2 args in one go when we
// need that.
match a[0].as_str() {
"-o" | "--output" => {
if output_file.is_none() {
... | Rust | 0 |
:from(stdin_buffer));
}
None
}
pub fn read_bytes_from_path(path: &str) -> Result<Bytes, StorkCommandLineError> {
match (path, read_stdin_bytes()) {
("-", Some(stdin)) => Ok(stdin),
("-", None) => Err(StorkCommandLineError::InteractiveStdinNotAllowed),
// handle ("", Some) or ("", N... | Rust | 0 |
r/unrar/strfn.cpp")
.file("vendor/unrar/pathfn.cpp")
.file("vendor/unrar/smallfn.cpp")
.file("vendor/unrar/global.cpp")
.file("vendor/unrar/file.cpp")
.file("vendor/unrar/filefn.cpp")
.file("vendor/unrar/filcreat.cpp")
.file("vendor/unrar/archive.cpp")
.fi... | Rust | 0 |
to represent the status.
///
/// This is invoked on a transaction's primary lock. The lock may be generated by either
/// [`AcquirePessimisticLock`](CommandKind::AcquirePessimisticLock) or
/// [`Prewrite`](CommandKind::Prewrite).
pub struct CheckTxnStatus {
/// The primary key of the transaction.
pub primary_k... | Rust | 0 |
0x60..=0x6B,
0x6D..=0x6F,
0xBA..=0xC2,
0xDB..=0xDF,
0xE1..=0xE4,
];
/// Bits of lparam indicating scan code, including extended bit.
const SCAN_MASK: LPARAM = 0x1ff_0000;
/// Determine whether there are more messages in the queue for this key event.
///
/// When this function returns `false`, there... | Rust | 0 |
import requests
import bs4
import re
from datetime import datetime
from waste_collection_schedule import Collection # type: ignore[attr-defined]
TITLE = "Basildon Council"
DESCRIPTION = "Source for basildon.gov.uk services for Basildon Council, UK."
URL = "https://basildon.gov.uk"
TEST_CASES = {
"Test_001": {"po... | Python | 1 |
.to_be_bytes());
md5.finalize().to_vec()
}
fn create_client_acceptor(key: &str, cert: &str) -> crate::Result<TlsAcceptor> {
let key = load_key(key)?;
let cert = load_certs(cert)?;
//把服务端证书加入 root,以信任由服务端证书签发的客户端证书
let mut root = RootCertStore::empty();
root.add(&cert[0]).map_err(err!())?;
... | Rust | 0 |
or(true) &&
removed_remote_ip == remote_ip && removed_remote_port == remote_port &&
removed_remote_port == remote_port && removed_remote_port == remote_port
);
}
ret
}
/// Sends a UDP packet on an existing connection.
///
/// # Errors
///
/// On error, the original `body` is re... | Rust | 0 |
lot unoptimized file
///
/// recommend **SSD** for tmp_dir
pub fn plot_unoptimized_file(addr: &Address, start: usize, end: usize, tmp_dir: &Path) -> PlotFile {
assert!(tmp_dir.is_dir());
// create file object
let tmp = Path::new(tmp_dir).join(format!(
"unoptimized.{}-{}-{}.tmp",
hex::encode... | Rust | 0 |
stancePath(InstancePathInner);
impl InstancePath {
pub(crate) fn new(inner: InstancePathInner) -> Self {
Self(inner)
}
#[inline]
pub(crate) fn push(&self, value: impl Into<PathChunk>) {
self.borrow_mut().push(value.into())
}
#[inline]
pub(crate) fn pop(&self) {
self.... | Rust | 0 |
# -*- coding: utf-8 -*-
# Příliš žluťoučký kůň úpěl ďábelské ódy - testovací pangram
"""_summary_
14_move.py
Vytvořte jednoduchou terminálovou aplikaci, která umožní hráči ovládat pohybující se
kostičku (O) po hrací ploše. Cílem je sebrat co nejvíce hvězdiček (*) umístěných
na hrací ploše.
Zadání úlohy
Vaším úkolem... | Python | 1 |
e,
Awaitable[retriever_service.BatchCreateChunksResponse],
],
]:
raise NotImplementedError()
@property
def get_chunk(
self,
) -> Callable[
[retriever_service.GetChunkRequest],
Union[retriever.Chunk, Awaitable[retriever.Chunk]],
]:
raise No... | Python | 1 |
import pytest
import torch
from zeta.utils.cuda_memory_wrapper import track_cuda_memory_usage
def test_track_cuda_memory_usage_no_cuda():
@track_cuda_memory_usage
def test_func():
return "Hello, World!"
assert test_func() == "Hello, World!"
@pytest.mark.skipif(
not torch.cuda.is_available(... | Python | 1 |
# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries
# SPDX-FileCopyrightText: 2024 Jose D. Montoya
#
# SPDX-License-Identifier: MIT
# Simple demo of the VCNL4010 proximity sensor using a built-in display.
import time
import board
from adafruit_display_text.bitmap_label import Label
from displayio import ... | Python | 1 |
import json
import sentencepiece as spm
import numpy as np
import seaborn as sns
from collections import Counter
from scipy.spatial.distance import jensenshannon
import matplotlib.pyplot as plt
import os
# 加载sentencepiece模型
sp = spm.SentencePieceProcessor()
sp.load('/mnt/e/unmt/acl22-sixtp/models/xlmrL_base/sentencep... | Python | 1 |
(())
}
#[tokio::test]
async fn memory_child_layer_removals_sp() {
let store = MemoryLayerStore::new();
child_layer_removals_sp(&store, false).await.unwrap();
}
#[tokio::test]
async fn directory_child_layer_removals_sp() {
let dir = tempdir().unwrap();
let store ... | Rust | 0 |
push(
match bytes.pop() {
Some(byte) => format!("{:x}", byte).to_string(),
_ => panic!("Error!"),
}
);
}
let h: String = pdu[0..1].join("");
let t: String = pdu[2..3].join("");
bytes.reverse();
At... | Rust | 0 |
f.source_adjudicator.get_type_display()])
else:
row.extend([""] * 3)
if f.source_team:
team = f.source_team.team
row.extend([team.id, team.short_name, f.source_team.get_result_display()])
else:
row.extend([""] * 3)
... | Python | 1 |
VERSION="20250128065759" | Python | 1 |
mized graph
// and an expected graph
#[macro_export]
macro_rules! test_opts {
(
$name:ident,
$(use_default_passes = $use_default_passes:expr,)?
$(passes = $passes:expr,)?
$(tape_len = $tape_len:expr,)?
$(step_limit = $step_limit:expr,)?
$(input = [$($input:expr... | Rust | 0 |
ame_error");
let response_msg = GetBleNameRes { ble_name };
encode_message(response_msg)
}
pub fn set_ble_name(data: &[u8]) -> Result<Vec<u8>> {
let request: SetBleNameReq = SetBleNameReq::decode(data).expect("ble_action");
device_manager::set_ble_name(request.ble_name)
.ok()
.expect(... | Rust | 0 |
frames_from_duration(&self, duration: zx::Duration) -> usize {
frames_from_duration(self.frames_per_second as usize, duration)
}
/// Return an amount of time that guarantees that `frames` frames has passed.
/// This means that partial nanoseconds will be rounded up, so that
/// [time, time + d... | Rust | 0 |
eval())
self.assertEqual(2, tf.rank(t_value).eval())
t = tf.constant(t_value)
self.assertAllEqual((2, 2), tf.shape(t).eval())
self.assertEqual(4, tf.size(t).eval())
self.assertEqual(2, tf.rank(t).eval())
def testSparseShape(self):
with self.test_session():
sp_value = tf.Spars... | Python | 1 |
ard {
champion_id: None,
skins: None,
}
}
}
extern crate autograd as ag;
extern crate ndarray;
#[test]
fn scalar_add() {
ag::with(|g| {
let z: ag::Tensor<f64> = 3. + g.ones(&[3]) + 2.;
assert_eq!(z.eval(&[]), Ok(ndarray::arr1(&[6., 6., 6.]).into_dyn()));
})... | Rust | 0 |
test_masking_scalar!(int_f64_b2, Integer, f64, 100, 10);
test_masking_scalar!(int_f64_b4, Integer, f64, 10_000, 10);
test_masking_scalar!(int_f64_b6, Integer, f64, 1_000_000, 10);
test_masking_scalar!(int_f64_bmax, Integer, f64, 10);
test_masking_scalar!(prime_f64_b0, Prime, f64, 1, 10);
test_... | Rust | 0 |
"C" fn call() {
let contract: Key = storage::store_function_at_hash(CONTRACT_NAME, Default::default()).into();
runtime::put_key(CONTRACT_NAME, contract)
}
#[cfg(test)]
mod tests;
mod response;
use actix_web::web::Path;
use actix_web::web::{Data, Query};
use actix_web::{Error, HttpRequest, HttpResponse};
use... | Rust | 0 |
|((min_val, max_val), p_i)| *p_i = rng.sample(Uniform::new(*min_val, *max_val)),
);
p
};
// randomly select a normal vector ~n ∈ IR |samples| by drawing each coordinate
// of ~n from a standard Gaussian distribution.
let mut n = [... | Rust | 0 |
# Combine both querysets
modifier_ids = set(item_modifiers.values_list('id', flat=True))
modifier_ids.update(material_modifiers.values_list('id', flat=True))
qs = self.model.objects.filter(id__in=modifier_ids)
else:
qs = item_modifiers
return q... | Python | 1 |
x=2
print("Learning Indentation")
print()
if x == 0:
print("In the If Block.")
print("Value of x is 0")
else:
print("In the else block.")
print("Value of x is non zero")
print()
print("This statement is out of if/else block.") | Python | 1 |
= f["mu"][:], f["sigma"][:]
else:
path = pathlib.Path(path)
files = sorted(
[file for ext in IMAGE_EXTENSIONS for file in path.glob("*.{}".format(ext))]
)
m, s = calculate_activation_statistics(
files, model, batch_size, dims, device, num_workers
)
... | Python | 1 |
flush().expect("Failed to flush stdout.");
Some(())
}
}
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use diagnostics_reader::{assert_data_tree, ArchiveReader, Data, Logs, Severity};
use f... | Rust | 0 |
l[torch.Tensor] = None,
response_mask: Optional[torch.Tensor] = None) -> dict:
"""
Compute batch-level metric statistics
Args:
log_probs: shape [batch_size, response_length] - log probabilities for each position
entropy: shape [batch_size, response_length] - ent... | Python | 1 |
or %}
/*
* Status
*/
{%- for p in range(n) %}
output wire [TLP_SEG_COUNT*SEQ_NUM_WIDTH-1:0] in{{'%02d'%p}}_sel_tlp_seq,
output wire [TLP_SEG_COUNT-1:0] in{{'%02d'%p}}_sel_tlp_seq_valid{% if not loop.last %},{% endif %}
{%- endfor %}
);
pcie_tlp_mux #(
.PORTS({{n}}),
.TLP_... | Python | 1 |
OK, we now have a list of requirements that can't all be
# satisfied at once.
# A couple of formatting helpers
def text_join(parts):
# type: (List[str]) -> str
if len(parts) == 1:
return parts[0]
return ", ".join(parts[:-1]) + " and " + part... | Python | 1 |
import setuptools
with open("README_PyPi.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="rfswarm-reporter",
version="1.5.2",
author="damies13",
author_email="damies13+rfswarm@gmail.com",
description="rfswarm reporter",
long_description=long_description,
long_description... | Python | 1 |
macro_rules! endian_impl {
($t:ty: $s:expr => $r:ident, $w:ident) => {
impl EndianConvert for $t {
#[inline]
fn from<B: ByteOrder>(s: &Self::Unaligned) -> Self {
B::$r(s)
}
#[inline]
fn to<B: ByteOrder>(self) -> Self::Unaligned {
... | Rust | 0 |
he number of cache entries.
'''
used = self.cache.size
dirty_size = 0
dirty_cnt = 0
for el in self.cache.values():
if el.dirty:
dirty_size += el.size
dirty_cnt += 1
if self.to_remove is None:
remove_cnt = 0
... | Python | 1 |
om_string
/// [Mnemonic::get_seed()]: ./mnemonic/struct.Mnemonic.html#method.get_seed
/// [Mnemonic::to_entropy()]: ./mnemonic/struct.Mnemonic.html#method.to_entropy
/// [Seed]: ./seed/struct.Seed.html
/// [Seed::as_bytes()]: ./seed/struct.Seed.html#method.as_bytes
/// [Seed::as_hex()]: ./seed/struct.Seed.html#method.a... | Rust | 0 |
und(adjusted_score)))
adjusted_scores[score_type] = adjusted_score
return adjusted_scores
def _calculate_overall_score(self,
adjusted_scores: Dict[str, int],
quality_metrics: QualityMetrics) -> float:
... | Python | 1 |
ent,
whitespace_re=self.whitespace_re,
keep_typographic_whitespace=self.keep_typographic_whitespace,
)
if self.autolink is True:
lxml.html.clean.autolink(doc)
elif isinstance(self.autolink, dict):
lxml.html.clean.autolink(doc, **self.a... | Python | 1 |
t field_sizes = vec![(2, 2), (9, 3), (3, 4), (4, 7)];
// n
// * * * * * * *
// m * *
// * *
// * * * * * * *
for (m, n) in field_sizes {
let mut perimeter: Vec<Point> = vec![];
perimeter.append(&mut points_2(0, 0..n));
perimeter.append(&m... | Rust | 0 |
# Add the root path of the dmrgpy library
import os ; import sys ; sys.path.append(os.getcwd()+'/../../../src')
import numpy as np
from dmrgpy import spinchain
n = 10
# create a random spin chain
spins = [2 for i in range(n)] # spin 1/2 heisenberg chain
# create first neighbor exchange
sc = spinchain.Spin_Chain(spin... | Python | 1 |
ost_process_fn = get_intervals_as_list,
post_process_fn = get_intervals_as_list_after_anchor(anchor),
max_new_tokens = 100,
)
## 2. answer question (log-likelihood classifier) ##
# egoschema QA mistral (log-likelihood eval)
prompt_templates['qa_ll_mistral'] = Pr... | Python | 1 |
import spacy
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
# Carregando o modelo de linguagem do Spacy
nlp = spacy.load('pt_core_news_lg')
# Função para pré-processar e etiquetar ... | Python | 1 |
".to_string())))
.wait();
res
}
}
#[derive(Clone, Debug)]
pub struct Group {
pub id: u8,
pub procedure_key: cap9_std::SysCallProcedureKey,
pub users: HashSet<Address>,
}
<gh_stars>0
mod wrappers;
use std::alloc::{dealloc, Layout};
use frost_secp256k1::{Participant, Parameters, key... | Rust | 0 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
Output(ParameterMode),
JumpIfTrue(ParameterMode, ParameterMode),
JumpIfFalse(ParameterMode, ParameterMode),
LessThan(ParameterMode, ParameterMode),
Equal(ParameterMode, ParameterMode),
Halt,
}
impl TryFrom<i32> for Opcode {
type Error = InvalidOpcode;
fn try_from(code: i32) -> Result<Sel... | Rust | 0 |
.clean("<my-tag my-attr>test</my-tag> <span>mess</span>").to_string();
/// assert_eq!("<my-tag my-attr=\"\">test</my-tag> <span>mess</span>", a);
pub fn add_tag_attributes<
T: 'a + ?Sized + Borrow<str>,
U: 'a + ?Sized + Borrow<str>,
I: IntoIter<Item = &'a T>,
>(
&mut... | Rust | 0 |
user=os.getenv('HBNB_MYSQL_USER'),
passwd=os.getenv('HBNB_MYSQL_PWD'),
db=os.getenv('HBNB_MYSQL_DB')
)
cursor1 = dbc1.cursor()
cursor1.execute('SELECT * FROM users WHERE id="{}"'.format(new.id))
result = cursor1.fetchone()
cursor1.execute('SELECT COU... | Python | 1 |
############################################################################
# Copyright (C) SchedMD LLC.
############################################################################
import atf
import pytest
import re
# Setup
@pytest.fixture(scope="module", autouse=True)
def setup():
atf.require_config_parameter(... | Python | 1 |
"""4) Implemente una simulación de un entrenamiento de carrera de posta para un equipo de
cuatro integrantes. En este tipo de carreras el primer integrante se coloca en línea de
largada y los otros tres en posiciones más adelantadas. Cuando la carrera comienza el
primer integrante debe correr hasta la posición del inte... | Python | 1 |
obj,
fmt,
subformats=subformats,
addStartDelay=True,
)
with open(fp, 'rb') as f:
binaryMidiData = f.read()
binaryBase64 = base64.b64encode(binaryMidiData)
s = common.SingletonCounter()
outputId = 'midiPlayerDiv' + str(s())
load_require_script = '''
... | Python | 1 |
check(x[:1].reshape([]), y)
check(x[-1:].reshape([]), y)
def test_unary_ufunc_where_same(self):
# Check behavior at wheremask overlap
ufunc = np.invert
def check(a, out, mask):
c1 = ufunc(a, out=out.copy(), where=mask.copy())
c2 = ufunc(a... | Python | 1 |
f.write(img_response.content)
print(f"已保存: {filename}")
except Exception as e:
print(f"保存图片时出错: {str(e)}")
continue
else:
... | Python | 1 |
html! {
<>
{
match self.page {
Page::Daily => self.view_daily(),
Page::History => self.view_history(),
Page::Config => self.view_config(),
}
}
{ self.view_nav() }
</>... | Rust | 0 |
# http://mvapich.cse.ohio-state.edu/benchmarks/
from mpi4py import MPI
def osu_bcast(
BENCHMARH="MPI Broadcast Latency Test",
skip=1000,
loop=10000,
skip_large=10,
loop_large=100,
large_message_size=8192,
MAX_MSG_SIZE=1 << 20,
):
comm = MPI.COMM_WORLD
myid = comm.Get_rank()
nu... | Python | 1 |
from selenium.webdriver.common.by import By
from pages.base_page_sauce import BasePage
from time import sleep
from seleniumpagefactory import PageFactory
class ProductPage(BasePage, PageFactory):
locators = {
"buttonsAddToCart": (By.XPATH, "//button[contains(@id, 'add-to-cart')]"),
"QuantElementos... | Python | 1 |
from typing import Sequence
from uuid import UUID
from fastapi import APIRouter, Depends
from coworld.controllers.dishes import DishController
from coworld.dependencies import get_dish_controller
from coworld.models.dishes import DishCreate, DishUpdate, Category
from coworld.models.models import Dish, DishInMenu
route... | Python | 1 |
#!/usr/bin/env python3
def aes():
sizes = ["128", "256"]
styles = ["", "Siv"]
for size in sizes:
for style in styles:
name = f"Aes{size}Gcm{style}"
if style == "":
path = f"aes_gcm::{name}"
else:
path = f"aes_gcm_siv::{name}"
... | Python | 1 |
input_vec), 2);
// 3
input_vec = vec![2, 4, 3, 5, 1];
assert_eq!(first_duplicate(input_vec), -1);
// 4
input_vec = vec![1];
assert_eq!(first_duplicate(input_vec), -1);
// 5
input_vec = vec![5, 5, 5, 5, 5];
assert_eq!(first_duplicate(input_vec), 5);
// 6
input_vec = vec![2, 1]... | Rust | 0 |
# training scripts for the nerf-synthetic datasets
import os
import GPUtil
from concurrent.futures import ThreadPoolExecutor
import time
import itertools
scenes = ["ship", "drums", "ficus", "hotdog", "lego", "materials", "mic", "chair"]
factors = [1]
output_dir = "exp_nerf_synthetic/release"
dataset_dir = "nerf_syn... | Python | 1 |
>())).data as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(IWKV_val),
"::",
stringify!(data)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<IWKV_val>())).size as *const _ as usize },
8usize,
... | Rust | 0 |
<'ctx> {
self.void_type.get_context()
}
/// Creates a `FunctionType` with this `VoidType` for its return type.
/// This means the function does not return.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
... | Rust | 0 |
# 将RGB值转换为XYZ空间
# rgb < 1
# rgb [N, 3]
# if rgb.max() > 10:
# rgb = rgb / 255.
if rgb.max() > 10:
rgb = rgb / 255.
rgb = torch.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4)
m = torch.tensor([[0.4124564, 0.3575761, 0.1804375],
[0.2126729,... | Python | 1 |
First, x, y), plane1 && x == 123);
assert_eq!(vmem.get_plane(Plane::Second, x, y), plane2 && x == 123);
}
assert_eq!(vmem.get_plane(Plane::First, 104, y), false);
assert_eq!(vmem.get_plane(Plane::Second, 104, y), false);
}
// S... | Rust | 0 |
from modulo_morse import texto_morse
from modulo_sonidos import morse_sonido
def menu():
numero = int(input("\n1.Traducir texto a codigo morse \n2.Reproducir codigo morse del texto codificado\n3.Salir del programa \n\nSeleccione una opción: "))
return numero
opcion = menu()
texto = ''
while 0 < opcion ... | Python | 1 |
import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''WordPress DZS-VideoGallery Plugin Reflected Cross-Site Scripting''',
"description": '''Multiple cross-site scripting vulnerabilities in deploy/designer/preview.php in the Digital Zoom Studio (DZS) Vide... | Python | 1 |
ask is impossible. **You can do it!**
""".strip()
self.ready()
def process_interpreter_command(self, text):
"""
Handles a text request.
"""
assistant_text = ""
if not self.abort:
try:
for chunk in self.interpreter.chat(text, display=T... | Python | 1 |
x.timelog.mark(format_args!("Step: {:?}", self))
.map_err(|e| format!("Can't write timelog: {}", e)));
}
Ok(())
}
}
use ockam_core::Message;
use ockam_message_derive::Message;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Message)]
pub struct PortalMessage {
... | Rust | 0 |
two main components:
//! * A list of batches that together represent a contiguous interval of time. For example, if the
//! "earliest" batch in a trace represents data from [t0, t3), then the next batch has to start from
//! t3.
//! * A compaction frontier. Periodically, the coordinator tells the compacter... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.