text string | label_name string | labels int64 |
|---|---|---|
{ @vtag $stack ($($tail)*) }
};
// End of openging tag
(@vtag $stack:ident (> $($tail:tt)*)) => {
html_impl! { $stack ($($tail)*) }
};
// Self-closing of tag
(@vtag $stack:ident (/ > $($tail:tt)*)) => {
$crate::macros::child_to_parent(&mut $stack, None);
html_impl! { $st... | Rust | 0 |
_allclose(a, a_expected)
def test_generate_arrays_dummy_model(self):
# Caffe dummy network interaction test Grace Hopper image)
# Construct network with an empty model just to see that our
# interaction with the Caffe API is successful. We expect a
# zero-valued descriptor vector.
... | Python | 1 |
ata
pub(crate) partition_id: PartitionId,
/// Id of to-be-created parquet file of this data
pub(crate) object_store_id: Uuid,
/// data
pub(crate) data: Arc<QueryableBatch>,
}
/// Queryable data used for both query and persistence
#[derive(Debug, PartialEq, Clone)]
pub struct QueryableBatch {
... | Rust | 0 |
e = Double(2.302585092994046e0, -2.1707562233822496e-16);
}
use std::convert::From;
use std::mem;
use std::str::FromStr;
use gio::{
IOStream, IOStreamExt, InputStreamExtManual, OutputStreamExtManual, SocketClient,
SocketClientExt, SocketConnection, TlsCertificateFlags,
};
use glib::source::PRIORITY_DEFAULT;
us... | Rust | 0 |
F16" => KeyCode::F16,
"F17" => KeyCode::F17,
"F18" => KeyCode::F18,
"F19" => KeyCode::F19,
"F20" => KeyCode::F20,
"F21" => KeyCode::F21,
"F22" => KeyCode::F22,
"F23" => KeyCode::F23,
"F24" => KeyCode::F24,
"F25" => KeyCode::F25,
"F26" => KeyCode::F26,
"F27" => KeyCode::F27,
"F28" => ... | Rust | 0 |
height,
)?;
let store = if is_fully_compacted(&store) {
store // initial import and full compaction are over
} else if config.jsonrpc_import {
// slower: uses JSONRPC for fetching blocks
index.reload(&store); // load headers
index.update(&store, &signal)?;
full_compac... | Rust | 0 |
ompound data structure containing hashed slices is computed
/// unambiguously from components' data.
pub fn hash_slice_as_elements<T, H>(slice: &[T], digest: &mut H)
where
T: Hash,
H: EndianInput,
{
for elem in slice {
elem.hash(digest);
}
}
#[cfg(test)]
mod tests {
use super::hash_bool_as_... | Rust | 0 |
he implementations of [`DipoDopo`] from four-tuples of
/// [`OptionalPadNum`]s to the corresponding [`Pads`] types.
impl<S, DI, DO, CK, SS> DipoDopo for Pads<S, DI, DO, CK, SS>
where
S: Sercom,
DI: OptionalPad,
DO: OptionalPad,
CK: OptionalPad,
SS: OptionalPad,
(DI::PadNum, DO::PadNum, CK::PadNu... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
File Name: ABAB_adv.py
Description: 整理ABAB型副词
Author: Rabbear Su
creation date: 2019/5/23
"""
import pandas as pd
import os
txt_path = 'data\\ABAB.txt'
with open(txt_path, 'r') as f:
lines = f.readlines()
f.close()
df = pd.DataFrame(columns=['副词', ... | Python | 1 |
::fs::write(rhs.path().join("my-file.txt"), "contents").unwrap();
///
/// directory_compare(
/// &mut vec!["my-file.txt"].into_iter(),
/// lhs.path(),
/// rhs.path()
/// ).unwrap();
/// ```
pub fn directory_compare<P, I, Q, R>(
golden_paths: &mut I,
lhs: Q,
rhs: R,
) -> Result<(), DirCompareErro... | Rust | 0 |
tion<String>,
#[serde(rename = "items", skip_serializing_if = "Option::is_none")]
pub items: Option<Vec<crate::models::LolItemSetsItemSetItem>>,
#[serde(rename = "showIfSummonerSpell", skip_serializing_if = "Option::is_none")]
pub show_if_summoner_spell: Option<String>,
#[serde(rename = "type", skip... | Rust | 0 |
return {
"success": False,
"error": f"Resource '{uri}' not found in any service. Last error: {last_error}",
"data": None,
"uri": uri,
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
}
e... | Python | 1 |
merate(indices_Ruido))
teremos algo do tipo: [(0,True), (1,True), ..., (5,False)...]
por isso o loop pede para me retornar i (1º elemento da tupla) caso valor (2º elemento)
seja verdadeiro
TUDO ISSO EU TENHO QUE FAZER PORQUE PYTHON NÃO ACEITA INDEXAÇÃO LÓGICA COMO R
existe outro jeito de f... | Python | 1 |
for i in range(renshu-1):
if piao[i]==m:
if i==0:
print("这轮投票导致你被干掉。")
quit()
else:
s.append(i)
for i in range(len(s)):
print("{}号".format(s[i]), end="")
print("因为这轮投票被干掉了。")
try:
sn1 = []
... | Python | 1 |
= addr_raw.parse().unwrap();
let backup_interval = conf.get::<u64>("persistence.interval").unwrap();
let backup_path = conf.get::<String>("persistence.path").unwrap();
logging::setup_logging(conf.get::<u64>("logging.verbosity").unwrap())
.expect("failed to initialize logging.");
info!("Merkava... | Rust | 0 |
# f(x) = f(x - 1)의 3번 반복, f(x - 1)의 1번과 빈칸 f(x - 1) 1번, f(x - 1)의 3번 반복.
# 이걸 2차원 배열로 하려고 하면 테트리스가 아니므로 구현 힘들 것 같음.
# 그럼 어떻게 ?
# f(x)면 f(x/3)에 해당하는 것을 첫번째 줄처럼 코딩해서 재귀 진행.
# 재귀를 진행하려면 몇 가지 생각을 해야한다.
# 1. 베이스 조건, 즉 재귀를 멈추는 조건이 필요하다.
# 2. 분해, 재귀 호출을 거듭하면서 베이스 조건에 가까워지게 인풋값을 조작해야한다.
# 3. 조합, 부분 답을 가지고 전체 답을 구하는 방법을 생각해본다... | Python | 1 |
.forced_exit_requests_schema()
.get_oldest_unfulfilled_request()
.await?;
Ok(request)
}
async fn delete_old_unfulfilled_requests(
&self,
deleting_threshold: chrono::Duration,
) -> anyhow::Result<()> {
let mut storage = self.connection_poo... | Rust | 0 |
#!/usr/bin/env python
# coding:utf-8
from __future__ import with_statement
__version__ = '1.0'
import sys
import os
import re
import time
import ctypes
import platform
def addto_startup_linux():
filename = os.path.abspath(__file__)
dirname = os.path.dirname(filename)
#you can change it to 'start.py' if ... | Python | 1 |
'''6. Em uma eleição presidencial existem quatro candidatos. Os votos são informados através de códigos.
Os dados utilizados para a contagem dos votos obedecem à seguinte codificação:
- 1,2,3,4 = voto para os respectivos candidatos;
- 5 = voto nulo;
- 6 = voto em branco;
Elabore um algoritmo que leia o código do ca... | Python | 1 |
the current session index.
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
pub fn set_session_index(index: SessionIndex) {
CurrentSessionIndex::set(index);
}
#[cfg(test)]
pub(crate) fn set_active_validators_ascending(active: Vec<ValidatorId>) {
ActiveValidatorIndices::set(
(0..active.le... | Rust | 0 |
_context → login_page → home_page
注意:
- 必须重新赋值,否则仍然停留在旧页面
:param login_page: 已登录的 LoginPage
:return: HomePage,已进入新窗口
"""
from pages.home_page import HomePage
home_pom = HomePage(login_page.page)
home_pom = home_pom.create_toutiao_campaign()
yield home_pom
@pytest.fixture(scope="c... | Python | 1 |
let mut guard = crate::communication::TEXTURE_IDS.lock();
for &(id, mat) in &[
(texid1, rask_engine::math::Mat3::identity()),
(texid2, rask_engine::math::Mat3::identity()),
] {
guard.ids.push(id);
self.st... | Rust | 0 |
_label));
get_memory(&mut res);
res.push(simple_op(AVMOpcode::Swap1));
res.push(set64_from_buffer(0));
set_memory(&mut res);
res.push(mk_label(end_label));
label = label + 2;
}
i => {
... | Rust | 0 |
atabase_exception_handler)
app.exception_handler(NodeConstructError)(node_construct_exception_handler)
app.exception_handler(ApplicationNotFound)(application_not_found_handler)
app.exception_handler(InteractionNotFound)(interaction_not_found_handler)
app.exception_handler(ApplicationInputTypeMismatch)(
... | Python | 1 |
from distutils.core import setup
from os.path import isdir
from itertools import product
# Gather our flightsim and any projXX packages that happen to exist.
all_packages = ['flightsim']
all_packages.extend([f"proj{a}_{b}" for (a,b) in product(range(10), repeat=2)])
packages = list(filter(isdir, all_packages))
setup(... | Python | 1 |
nimages = len(iml['features'])
images = []
if nimages > 0:
limages = imColl.toList(nimages).getInfo()
for im in limages:
if 'PRODUCT_ID' in im['properties']: ## Sentinel-2 image
fkey = 'PRODUCT_ID'
pid = im['properties'][fkey]
elif 'LAND... | Python | 1 |
.expect("failed to generate scenario");
// TODO Do something with it -- save it, launch it in sandboxmode, display some
// stats about it?
return Transition::Pop;
}
_ => unreachable!(),
},
... | Rust | 0 |
App;
pub use args::Args;
pub(crate) mod status;
<filename>src/bin/aoc24.rs
// Copyright 2018 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
//
// https://www.apache.org... | Rust | 0 |
from byzerllm.utils.client import ByzerLLM,InferBackend,Templates
import ray
import pytest
model_path = "/home/winubuntu/models/deepseek-coder-1.3b-instruct"
model_name = "chat"
class TestByzerLLMVLLMDeploy(object):
llm = None
def setup_class(self):
if ray.is_initialized():
ray.shutdown()... | Python | 1 |
fd, listener_fd, listener_read_event(key))?;
loop {
println!("requests in flight: {}", request_contexts.len());
events.clear();
// 将就绪的事件添加到 events vec 中,返回就绪的事件数量
let res = match syscall!(epoll_wait(
epoll_fd,
events.as_mut_ptr() as *mut libc::epoll_event,
... | Rust | 0 |
"""
Original code: https://github.com/kuangliu/pytorch-cifar/blob/master/utils.py
Some changes were done for added support
"""
import shutil
import sys
import time
_, term_width = shutil.get_terminal_size()
term_width = int(term_width)
TOTAL_BAR_LENGTH = 65.
last_time = time.time()
begin_time = last_time
d... | Python | 1 |
, parser);
buf
}
}
impl FromStr for Content {
type Err = anyhow::Error;
fn from_str(full_document: &str) -> Result<Self, Self::Err> {
let (toml_text, body) = full_document
.split_once(DOC_SEPERATOR)
.unwrap_or(("title = 'Untitled'", &full_document));
let hea... | Rust | 0 |
#!/usr/bin/env python3
#
# Copyright (C) VyOS Inc.
#
# 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 option) any later version.
#
# This l... | Python | 1 |
read--modify--write-api).\n\nFor information about available fields see [otg_hs_diepint7](otg_hs_diepint7) module"]
pub type OTG_HS_DIEPINT7 = crate::Reg<u32, _OTG_HS_DIEPINT7>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _OTG_HS_DIEPINT7;
#[doc = "`read()` method returns [otg_hs_diepint7::R](otg_hs_diepint7::R) r... | Rust | 0 |
nsforms, &enemies).join() {
// Determine whether we've collided
let enemy_x = enemy_transform.translation().x;
let enemy_y = enemy_transform.translation().y;
for (player_transform, _player) in (&transforms, &mut players).join() {
let player_x = player_tr... | Rust | 0 |
# coding: utf-8
"""
Dataddo Headless BETA API
Dataddo Headless BETA API
The version of the OpenAPI document: 1.0.0-beta.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from openapi_client.api.destinations_inte... | Python | 1 |
// cost 13790
parse_cubic_to_bytes_sub(
ark_ff::fields::models::cubic_extension::CubicExtField::<
ark_ff::fields::models::fp6_3over2::Fp6ParamsWrapper<ark_bn254::Fq6Parameters>,
>::new(c0, c1, c2),
_cubic_range_0,
SOLO_CUBIC_0_RANGE,
);
}
pub fn custom_quadratic... | Rust | 0 |
about.__version__
else:
version = get_minor_version(about.__version__)
r = requests.get(about.__compatibility__)
if r.status_code != 200:
msg.fail(
f"Server error ({r.status_code})",
f"Couldn't fetch compatibility table. Please find a package for your spaCy "
... | Python | 1 |
s_reader = reader.add_reader();
scope.spawn(move || {
bref.wait();
'outer: for i in 0..num_loop {
loop {
if let Some(val) = this_reader.pop() {
assert_eq!(i, val);
... | Rust | 0 |
l);
// Load standard substrate types.
types.load_schema(&opts.substrate_types)?;
// Load custom chain types.
types.load_schema(&opts.custom_types)?;
// Custom encodings.
types.custom_encode("Era", TypeId::of::<Era>(), |value, data| {
let era = value.cast::<Era>();
data.encode(era);
Ok(())
})... | Rust | 0 |
"]
pub type SLEEPEXIT_R = crate::R<bool, SLEEPEXIT_A>;
impl SLEEPEXIT_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SLEEPEXIT_A {
match self.bits {
false => SLEEPEXIT_A::DISABLED,
true => SLEEPEXIT_A::ENABLED,
}
}
#[d... | Rust | 0 |
T_CODE: i32 = 101;
const SUCCESS_EXIT_CODE: i32 = 0;
const USE_SYSTEM_CONTRACTS: &str = "--use-system-contracts";
const TURBO: &str = "turbo";
lazy_static! {
static ref WORKSPACE_PATH_ARG: String =
format!("--workspace-path={}/../../", env!("CARGO_MANIFEST_DIR"));
static ref TEST_DIR: TempDir = TempDir... | Rust | 0 |
import re
from statistics import geometric_mean
benchmark_text = """
k: 7168; m: 1024; n: 1536; seed: 8135
⏱ 467 ± 0.6 µs
⚡ 462 µs 🐌 512 µs
k: 1536; m: 1024; n: 3072; seed: 6251
⏱ 108 ± 0.2 µs
⚡ 107 µs 🐌 129 µs
k: 7168; m: 1024; n: 576; seed: 12346
⏱ 487 ± 1.0 µs
⚡ 465 µs 🐌 509 µs
k: 256; m: 1024; n: 7168;... | Python | 1 |
_trait::async_trait;
use git_url_parse::GitUrl;
use log::debug;
use reqwest::Method;
use serde_json::json;
pub struct GitHubRepository {
repo: String,
client: GitHubClient,
}
impl GitHubRepository {
pub async fn init(remote_url: &GitUrl) -> Result<Self> {
let profile = load_profile().await?;
... | Rust | 0 |
.is_static && !env::var_os("VCPKGRS_DYNAMIC").is_some() {
return Err(Error::RequiredEnvMissing("VCPKGRS_DYNAMIC".to_owned()));
}
let mut lib = Library::new(vcpkg_target.is_static);
if self.emit_includes {
lib.cargo_metadata.push(format!(
"cargo:i... | Rust | 0 |
ve_id_set)
def __getitem__(self, track_id):
try:
return self.id_ts_dict[track_id]
except KeyError:
raise IndexError
def get_all_track_id(self):
return sorted(self.id_ts_dict)
def get_max_track_id(self):
return max(self.id_ts_dict) if self.id_ts_dict... | Python | 1 |
ap();
db.add_leaf(h_l_3.clone()).unwrap();
let n_0_1 = hasher
.hash_tree_nodes(h_l_0.clone(), h_l_1.clone())
.unwrap();
let n_2_3 = hasher
.hash_tree_nodes(h_l_2.clone(), h_l_3.clone())
.unwrap();
db.add_full_subtree_root(n_0_1.clone()).u... | Rust | 0 |
Tone(C, Sharp, ..) |
Tone(D, Flat, ..) => 2,
Tone(D, Natural, ..) => 3,
Tone(D, Sharp, ..) |
Tone(E, Flat, ..) => 4,
Tone(E, Natural, ..) => 5,
Tone(F, Natural, ..) => 6,
Tone(F, Sharp, ..) |
Tone(G, Fla... | Rust | 0 |
from PIL import Image
ascii_characters_by_surface = (
'`^",:;Il!i~+_-?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$'
)
def main():
image = Image.open("test1.jpg")
image = image.resize((100, 100))
# you can first resize the image if needed
# image = image.resize((width, height))
ascii_ar... | Python | 1 |
# -*- coding: utf-8 -*-
"""
強化學習代理包裝器
此模組將強化學習代理包裝為多代理系統中的一個代理,
實現與其他投資大師代理的協作。
主要功能:
- RL代理包裝和適配
- 決策格式轉換
- 性能監控和統計
- 與協調機制整合
- 自適應學習能力
整合特色:
- 無縫整合到多代理系統
- 保持RL代理的學習能力
- 支援多種RL算法
- 提供統一的決策接口
"""
import logging
import numpy as np
import pandas as pd
from typing import Dict, List, Any, Optional, Tuple
from dataclas... | Python | 1 |
let stride = width as i32 * 4;
libwebp_sys::WebPEncodeRGBA(
input.as_ptr(),
width as i32,
height as i32,
stride,
quality_factor as f32,
&mut out_buf,
)
}
DynamicImage::ImageLuma8(input) => {
let stride = width as i32 * 3;
let convert... | Rust | 0 |
#! /usr/bin/env python
import pybedtools as pyb
import sys
version= '0.1.0'
docstring= """Intersect two bed files and return the numbers for a venn diagram.
Usage
vennBedTwoWay.py a.bed b.bed
>>> c(only_a: 115841, only_b: 111798, both: 66130)
Within R:
xv<- system('vennBedTwoWay.py a.bed b.bed', intern= TRUE)
ab<- ... | Python | 1 |
f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Shape::")?;
match self {
Shape::Polyline(shp) => write!(f, "{}", shp),
Shape::PolylineM(shp) => write!(f, "{}", shp),
Shape::PolylineZ(shp) => write!(f, "{}", shp),
Shape::Point(shp) => write!(f, "{}", s... | Rust | 0 |
]
#[inline(always)]
pub fn rxpwdrx(&mut self) -> RXPWDRX_W {
RXPWDRX_W { w: self }
}
}
<reponame>Jqnxyz/OxidizeBot<filename>bot/src/irc/chat_log.rs
use crate::api::{twitch::Channel, Twitch};
use crate::emotes;
use crate::injector;
use crate::irc;
use crate::message_log;
use crate::settings;
use crat... | Rust | 0 |
>,
ap2: Option<f64>,
ap3: Option<f64>,
ap4: Option<f64>,
ap5: Option<f64>,
as1: Option<f64>,
as2: Option<f64>,
as3: Option<f64>,
as4: Option<f64>,
as5: Option<f64>,
valid: Option<f64>,
__index_level_0__: Option<i64>,
}
#[bench]
fn parquet_10k(b: &mut Bencher) {
let file = "amadeus-testing/parquet/10k-v2.pa... | Rust | 0 |
atley consume and drop the guard
pub fn notify_filter<F>(&mut self, f: F) where F: Fn(&T) -> bool {
let guard = &mut self.guard;
let mut i = guard.waiters.len();
while i > 0 {
let notify = f(&guard.waiters[i - 1].1);
if notify {
let (tx, _) = guard.waiters.swap_remove(i - 1);
if let Err(_) = tx.se... | Rust | 0 |
263,
"timer_getoverrun": 262,
"timer_gettime": 261,
"timer_gettime64": 408,
"timer_settime": 260,
"timer_settime64": 409,
"timerfd_create": 322,
"timerfd_gettime": 327,
"timerfd_gettime64": 410,
"timerfd_settime": 326,
"timerfd_settime64": 411,
"times": 43,
"tkill": 238,
... | Python | 1 |
elf.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = "Possible values of the field `CLKSEL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CLKSELR {
#[doc = "No UART clock. This is the low power default. v... | Rust | 0 |
},
_ => panic!("sussy")
}
}
// let precedence_op = operators.get();
}
}
}
while let Some(u) = p_op_stack.pop() {
p_output.push(u);
}
output
}
pub fn postfix_cal... | Rust | 0 |
_wrapped() {
let later = super::ActiveTimer {
instant: 2u32,
set_at: 1u32,
};
let earlier = super::ActiveTimer {
instant: 3u32,
set_at: 1u32,
};
assert_eq!(super::left_is_later(later, earlier), false);
}
#[test]
pub fn ... | Rust | 0 |
:encode(&data),
"Session Key: {},
data: {},
Got data: {}",
hex::encode(session_key.as_le()),
hex::encode(&original_data),
hex::encode(&data)
);
// Bypass checking seeds and proofs because they aren... | Rust | 0 |
Wheel)
/// .discrete(Axis::Vertical, 6)
/// .value(Axis::Vertical, 30, time)
/// .stop(Axis::Vertical);
/// ```
#[derive(Copy, Clone, Debug)]
pub struct AxisFrame {
source: Option<AxisSource>,
time: u32,
axis: (f64, f64),
discrete: (i32, i32),
stop: (bool, bool),
}
impl AxisFrame {
... | Rust | 0 |
separators=(',', ':'))
return data.encode('utf-8')
import random
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', type=int, default=256)
parser.add_argument('--width', type=int, default=256)
parser.add_argument('--port', type=int, default=11023)
parser.add_argument('--env_name... | Python | 1 |
_noncpg_thread") }
}
pub fn output_cpg_thread(chash: Arc<ConfHash>, hdr: Arc<VcfHeader>, r: Recv, tp: TPool) {
let output = chash.get_str("cpgfile").expect("CpG output filename is missing");
let outfile = open_output_file(output, &chash, tp);
debug!("output_cpg_thread starting up");
output_handler(&chash, &hdr, r,... | Rust | 0 |
uvioError};
use futures_lite::StreamExt;
use crate::consume::ConsumeLogOpt;
use crate::consume::logs_output::print_record;
use crate::ConsumerError;
use fluvio_sc_schema::ApiError;
// -----------------------------------
// SPU - Fetch Loop
// -----------------------------------
/// Fetch log continuously
#[allow(cli... | Rust | 0 |
n add_like(db, snippet, current_user.id)
@router.delete("/{snippet_id}/like", response_model=Snippet)
def unlike_snippet_endpoint(
*,
db: Session = Depends(get_db),
snippet_id: UUID,
current_user: User = Depends(get_current_user)
) -> Any:
"""
Remove like from a snippet
"""
snippet = g... | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright 2024 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... | Python | 1 |
, Clone, PartialEq, Serialize, Deserialize)]
pub struct Node {
/// The labels attached to this node.
pub labels: Vec<String>,
/// The properties of this node.
pub properties: HashMap<String, Scalar>,
}
// Macro generates generic "From" implementations to allow
// tuples/vecs-of-tuples to be extracted f... | Rust | 0 |
from datetime import datetime
import numpy as np
from pandas import (
DatetimeIndex,
Series,
)
import pandas._testing as tm
def test_series_set_value():
# GH#1561
dates = [datetime(2001, 1, 1), datetime(2001, 1, 2)]
index = DatetimeIndex(dates)
s = Series(dtype=object)
s._set_value(dat... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING
from sqlalchemy import Enum
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.orm import Mapped, relationship, mapped_column
from app.core.models import dto, enums
from .base import Base, bigint, UTC_datetime
if TYPE_CHECKING:
fr... | Python | 1 |
.to_lexical_with_options(&mut buffer, &options)
);
assert_eq!(
&b"-80000000000000000000000000000000"[..],
(170141183460469231731687303715884105728u128 as i128)
.to_lexical_with_options(&mut buffer, &options)
);
}
#[test]
#[cfg(feature... | Rust | 0 |
# =========================================================================
# FILE: sch_convert.py
#
# USAGE: ---
#
# DESCRIPTION: This is program to create a batch file
# Used to convert schematics in bulk
#
# OPTIONS: ---
# REQUIREMENTS: ---
# BUGS: ---
# NOTES: ---
# ... | Python | 1 |
from acesso.maquinas import usuarios
#Processa a Resposta do Coordenador
def processar_resposta_acesso(email, sent_emails, sender):
corpo_email = email.raw
#Verifica se o email é uma resposta de pedido de acesso
if "Nome completo do aluno:" in corpo_email:
#Guarda o nome do aluno que est... | Python | 1 |
import pytest
from fastid.cache.exceptions import KeyNotFoundError
from fastid.cache.storage import CacheStorage
async def test_keys(cache: CacheStorage, mock_record: dict[str, str]) -> None:
keys = await cache.keys()
assert len(keys) == 1
assert mock_record["key"] in keys
async def test_get(cache: Cac... | Python | 1 |
user_id=user_id)['user_lang']
get_fat_count = len(get_positionsx(category_id=category_id))
get_category = get_categoryx(category_id=category_id)
if lang == "ru":
await call.message.edit_text(f"<b>🗃 Категория: <code>{get_category['category_name']}</code></b>\n"
... | Python | 1 |
//! ```
//! # async_std::task::block_on(async {
//! #
//! use async_std::task;
//!
//! let handle = task::spawn(async {
//! 1 + 2
//! });
//! assert_eq!(handle.await, 3);
//! #
//! # })
//! ```
#[doc(inline)]
pub use std::task::{Context, Poll, Waker};
#[doc(inline)]
pub use async_macros::ready;
pub use block_on... | Rust | 0 |
UST_LOG_ENV_NAME, "trace")
}
_ => return,
};
env_logger::builder()
.format(|buf, record| {
match record.module_path() {
Some(module_path) if module_path.starts_with(IT_MODULE_PATH) => {
writeln!(buf, "[host] {}", record.args())
... | Rust | 0 |
nfig.pop("model_type")
audio_encoder_config = kwargs.pop("audio_encoder")
audio_encoder_model_type = audio_encoder_config.pop("model_type")
decoder_config = kwargs.pop("decoder")
self.text_encoder = AutoConfig.for_model(text_encoder_model_type, **text_encoder_config)
self.audi... | Python | 1 |
language == "zh" else "Cannot add items to a non-container type. Please use the context menu on dictionary or array items.",
"Create Dict": "创建字典" if self.language_manager and self.language_manager.current_language == "zh" else "Create Dict",
"Create Array": "创建数组" if self.language_manager and s... | Python | 1 |
def fibonacci():
n1, n2 = 0, 1
while True:
yield n1
n1, n2 = n2, n1 + n2
generator = fibonacci()
for i in range(5):
print(next(generator))
print('\n')
generator = fibonacci()
for i in range(1):
print(next(generator))
| Python | 1 |
rror):
test_queue.kill(["bar", "foo", "foobar"], force=force)
kill_mock.assert_called_once_with(
{mock_entry_foo: "foo", mock_entry_bar: "bar"}, force
)
@pytest.mark.parametrize("status", ["FAILURE", "SUCCESS"])
def test_queue_iter_done_task(test_queue, mocker, status):
mock_entry = mocker... | Python | 1 |
"renditions": [{"url": "Va2FnZFo_GE"}],
},
{
"assetType": "URL",
"assetRole": "CAR",
"title": "More videos",
"description": "",
"renditions": [{"url": "https://www.youtube.com/watch?v=wfpCMkK1rKI"}],
},
{
... | Python | 1 |
q, e];
//println!("{:?} {:?}", minvec);
let end: usize = *minvec.iter().min().unwrap() ;
//println!("{}", end);
let outstring: String = charlist[pos..end].iter().collect();
if outstring.trim() != "" {
sentence_list.push(outstring.trim().to_string());
}
... | Rust | 0 |
ist"
assert len(replacements_core) == len(replacements), "Length of replacements does not match"
assert len(jacobian_core) == 1, "Jacobian should have one element"
assert len(precomputed_fs_core) == len(replacements), "Length of precomputed free symbols does not match"
# Test _forward_jacobian_norm_in_... | Python | 1 |
off::TCD11_DOFF_SPEC>,
_reserved_160_dma_tcd11_citer: [u8; 0x02],
#[doc = "0x1178 - TCD Last Destination Address Adjustment/Scatter Gather Address"]
pub tcd11_dlastsga: crate::Reg<tcd11_dlastsga::TCD11_DLASTSGA_SPEC>,
#[doc = "0x117c - TCD Control and Status"]
pub tcd11_csr: crate::Reg<tcd11_csr::TC... | Rust | 0 |
D3D_SVT_TEXTURECUBE);
pub const Sampler : SVT = SVT(D3D_SVT_SAMPLER);
pub const Sampler1D : SVT = SVT(D3D_SVT_SAMPLER1D);
pub const Sampler2D : SVT = SVT(D3D_SVT_SAMPLER2D);
pub const Sampler3D : SVT = SVT(D3D_SVT_SAMPLER3D);
pub cons... | Rust | 0 |
grators)} integrators.')
# # Get inventory.
# test_inventory = ccrs.get('inventory', limit=100, base=base)
# print(f'Accessed {len(test_inventory)} inventory.')
# # Get inventory_adjustments.
# test_inventory_adjustments = ccrs.get('inventory_adjustments', limit=100, base=base)
# print(f'Accessed {len(test_inventory_... | Python | 1 |
import numpy as np
def get_objects_from_label(label_file):
with open(label_file, 'r') as f:
lines = f.readlines()
objects = [Object3d(line) for line in lines]
return objects
def cls_type_to_id(cls_type):
type_to_id = {'Car': 1, 'Pedestrian': 2, 'Cyclist': 3, 'Van': 4}
if cls_type not in ... | Python | 1 |
sys.ps1 = '---'
""").lstrip()
with (tmpdir / 'foo-script.py').open('w') as f:
f.write(self.prep_script(tmpl))
cmd = [str(tmpdir / 'foo.exe')]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, st... | Python | 1 |
t_back(&mut self) -> Option<StatusEntry<'a>> {
self.range.next_back().and_then(|i| self.statuses.get(i))
}
}
impl<'a> ExactSizeIterator for StatusIter<'a> {}
impl<'statuses> StatusEntry<'statuses> {
/// Access the bytes for this entry's corresponding pathname
pub fn path_bytes(&self) -> &[u8] {
... | Rust | 0 |
`\"Win32_NetworkManagement_MobileBroadband\"`*"]
pub const MBN_BAND_CLASS_V: MBN_BAND_CLASS = 32i32;
#[doc = "*Required features: `\"Win32_NetworkManagement_MobileBroadband\"`*"]
pub const MBN_BAND_CLASS_VI: MBN_BAND_CLASS = 64i32;
#[doc = "*Required features: `\"Win32_NetworkManagement_MobileBroadband\"`*"]
pub const... | Rust | 0 |
}
fn is_delimited_identifier_start(&self, ch: char) -> bool {
ch == '"'
}
fn is_identifier_part(&self, ch: char) -> bool {
(ch >= 'a' && ch <= 'z')
|| (ch >= 'A' && ch <= 'Z')
|| (ch >= '0' && ch <= '9')
|| ch == '$'
|| ch == '_'
}
}
... | Rust | 0 |
SpeechGrammarState, SpeechGrammarWordType, SpeechInterference, SpeechLanguageId,
SpeechLexiconType, SpeechLoadOption, SpeechPartOfSpeech, SpeechRecoContextState,
SpeechRecoEvents, SpeechRecognitionType, SpeechRecognizerState, SpeechRetainedAudioOptions,
SpeechRuleAttributes, SpeechRuleState, SpeechRunS... | Rust | 0 |
run['objects']):
print('*** TIMED OUT WAITING FOR STRING MATCH')
exit(1)
if status in finishedStates:
break
if progress:
try:
progressPath = backupInfo['progressTaskId']
progressMonito... | Python | 1 |
from typing import List
from pydantic import BaseModel, Extra, Field
class QAA(BaseModel):
totalScore: int = Field(description='Total score')
isSharp: bool
sharpnessScore: int = Field(description='Sharpness score')
isEvenlyIlluminated: bool
illuminationScore: int = Field(description='Illumination... | Python | 1 |
// ...
println!("{}", my_string);
}
}
}
use std::cell::RefCell;
use std::borrow::Cow;
use std::error::Error;
use postgres::{Connection, TlsMode, types::{Type, ToSql}, rows::Row};
use serde_json::Value;
use chrono::{NaiveDate, NaiveTime, NaiveDateTime};
use crate::error::FromSqlError;
thread_loca... | Rust | 0 |
0.0F03290A3167EE"));
let count = ftoa(0.0293209862654321f64, 16, 16, 16, &mut buffer, format);
assert_eq!(&buffer[..count], b!("0.0781948518B3F7"));
let count = ftoa(0.01466049313271605f64, 16, 16, 16, &mut buffer, format);
assert_eq!(&buffer[..count], b!("0.03C0CA428C59FB8"));
... | Rust | 0 |
LPDWORD,
) -> LSTATUS;
pub fn RegGetValueW(
hkey: HKEY,
lpSubKey: LPCWSTR,
lpValue: LPCWSTR,
dwFlags: DWORD,
pdwType: LPDWORD,
pvData: PVOID,
pcbData: LPDWORD,
) -> LSTATUS;
pub fn RegCopyTreeW(
hKeySrc: HKEY,
lpSubKey: LPCWSTR,
... | Rust | 0 |
"@beep__bytes__0_5_6//:bytes",
"cc": "@beep__cc__1_0_62//:cc",
"lazy_static": "@beep__lazy_static__1_4_0//:lazy_static",
"libc": "@beep__libc__0_2_80//:libc",
"libz-sys": "@beep__libz_sys__1_1_2//:libz_sys",
"pin-project-lite": "@beep__pin_project_lite__0_1_12//:pin_project_lite",
"pkg-config":... | Rust | 0 |
self.cursor
}
/// Set the cursor to the given index, if valid
pub fn set_cursor(&mut self, index: usize) {
if index <= self.tokens.len() {
self.cursor = index
}
}
pub fn span<'a>(&'a self, start: usize, end: usize) -> &[T] {
&self.tokens[start..end]
}
p... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.