text string | label_name string | labels int64 |
|---|---|---|
"""develop tests"""
import sys
from unittest import mock
import pytest
from setuptools.dist import Distribution
from setuptools import SetuptoolsDeprecationWarning
@pytest.mark.skipif(sys.platform == 'win32', reason='non-Windows only')
@pytest.mark.xfail(reason="bdist_rpm is long deprecated, should we remove it? #... | Python | 1 |
QueryControl: u32 {
const Precise = VK_QUERY_CONTROL_PRECISE_BIT;
}
}
const VK_STENCIL_FACE_FRONT_BIT: VkStencilFaceFlagBits = 1;
const VK_STENCIL_FACE_BACK_BIT: VkStencilFaceFlagBits = 2;
const VK_STENCIL_FACE_FRONT_AND_BACK: VkStencilFaceFlagBits = 3;
const VK_STENCIL_FRONT_AND_BACK: VkStencilFaceFlagBi... | Rust | 0 |
port ImageCreateVariationParams as ImageCreateVariationParams
from .static_file_chunking_strategy import StaticFileChunkingStrategy as StaticFileChunkingStrategy
from .eval_custom_data_source_config import EvalCustomDataSourceConfig as EvalCustomDataSourceConfig
from .moderation_image_url_input_param import ModerationI... | Python | 1 |
esults_path)
torch.save(registration_results, results_path)
print("Saving:", metrics_path)
save_dict_as_json(metrics, metrics_path)
# Save points
if grouppoints_m is not None:
grouppoints_m_path = group_dir / f"points_m-{aug}.npy"
grouppoints_a_path =... | Python | 1 |
"""
解数独
编写一个程序,通过填充空格来解决数独问题
数独的解法需要遵循如下的规则:
1. 数字1-9在每一行只能出现一次
2. 数字1-9在每一列只能出现一次
3. 数字1-9在每一个以粗实现分隔的3*3宫内只能出现一次
可以使用 最小剩余值(MRV) 策略来选择待填充的空格,即优先填充限制最多的空格。这通常能大大减少递归次数。
"""
from typing import List
class Solution:
## 主程式
def solveSudoku(self,board:List[List[str]])->None:
self.board = board
... | Python | 1 |
or, if it blocks. If the timeout is negative then
/// the calling thread will be blocked forever.
///
/// The calling thread can only be woken up with a call to the `wake` intrinsic
/// once it has been blocked. Changing the memory behind `ptr` will not wake
/// the thread once it's blocked.
///
/// # Return value
///
... | Rust | 0 |
test::black_box(vec)
});
}
#[bench]
fn bench_push_nested_avec_elf(b: &mut Bencher) {
bench_push_nested::<
AVec<usize, DynamicAlloc>,
AVec<AVec<usize, DynamicAlloc>, DynamicAlloc>,
>(b);
}
#[bench]
fn bench_push_nested_avec_shared_elf(b: &mut Benc... | Rust | 0 |
from typing import Tuple
import ml_collections
import tensorflow as tf
from tensorflow import keras
def get_cifar_dataset(
config: ml_collections.ConfigDict,
) -> Tuple[tf.data.Dataset, tf.data.Dataset, tf.data.Dataset]:
"""Loads the CIFAR-10 dataset and prepares tf.data.Dataset objects."""
(x_train, y_t... | Python | 1 |
"""
Plugin for ResolveURL
Copyright (C) 2022 shellc0de
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
... | Python | 1 |
subtitle=video[1],
referrer=self.BASE_URL,
)
)
for sub_playlist in content.playlists:
substreams.append(
ProviderStream(
url=urljoin(content.base_uri, sub_playlist.uri),
... | Python | 1 |
"""Terminal dashboard for feed status."""
from __future__ import annotations
import curses
from .scheduling import get_feed_status
REFRESH_INTERVAL = 5
def _render(screen: curses.window) -> None:
"""Render the feed dashboard until ``q`` is pressed."""
curses.curs_set(0)
curses.start_color()
curses... | Python | 1 |
const_interval};
#[test]
fn decoration() {
use Decoration::*;
let mut xs = TupperIntervalSet::new();
assert_eq!(xs.decoration(), Trv);
xs.insert(TupperInterval::from(const_dec_interval!(0.0, 0.0)));
assert_eq!(xs.decoration(), Com);
xs.insert(TupperInterval::... | Rust | 0 |
"""
@author: jpzxshi
"""
import torch.nn as nn
from .module import Map
class FNN(Map):
'''Fully-connected neural network.
Note that
len(size) >= 2,
[..., N1, -N2, ...] denotes a linear layer from dim N1 to N2 without bias,
[..., N, 0] denotes an identity map (as output linear layer).
'''
de... | Python | 1 |
er.size_hint()
}
}
impl<T> DoubleEndedIterator for Drain<'_, T> {
#[inline]
fn next_back(&mut self) -> Option<T> {
self.iter
.next_back()
.map(|elt| unsafe { core::ptr::read(elt as *const _) })
}
}
impl<T> Drop for Drain<'_, T> {
fn drop(&mut self) {
/// Con... | Rust | 0 |
(&Value::Fixed(n, _), SchemaPiece::Fixed { size }) => n == *size,
(&Value::String(ref s), SchemaPiece::Enum { symbols, .. }) => symbols.contains(s),
(&Value::Enum(i, ref s), SchemaPiece::Enum { symbols, .. }) => symbols
.get(i as usize)
.map(|symbol| sy... | Rust | 0 |
turn {'groups': groups}
@json_api.route('/send_message', methods=['post'])
def send_message():
data = request.get_json()
type = data['type']
ids = data['ids']
group_id = data['gid']
files = data['files']
content = data['content']
if type == 'group':
send_type = data['send_type']
... | Python | 1 |
let x = self.x.ok_or(SynthesisError::AssignmentMissing)?;
let x2 = x2value.ok_or(SynthesisError::AssignmentMissing)?;
let x3 = x * x2;
x3value = Some(x3);
Ok((x, x2, x3))
},
)?;
cs.enfor... | Rust | 0 |
{
satoshis: 20,
lock_script: Script(vec![]),
},
],
lock_time: 0,
};
assert!(tx.validate(true, true, &utxos, &HashSet::new()).is_ok());
let mut tx_test = tx.clone();
tx_test.inputs = vec![];
assert!(... | Rust | 0 |
t Some(weap) = (*self.inv_ptr).get_weapon_by_type_mut(WeaponType::PolarStar) {}
}
1
}
pub(crate) fn new(plr_ptr: *mut Player, inv_ptr: *mut Inventory) -> LuaPlayer {
LuaPlayer {
valid_reference: true,
plr_ptr,
inv_ptr,
}
}
}
impl Drop fo... | Rust | 0 |
GNSteepestDescent(residual_module=residual_module_segm, num_iter=optim_iter,
detach_length=detach_length,
residual_batch_dim=1, compute_losses=True)
# Target model and Few-shot learner
target_model = ... | Python | 1 |
nventory.arrow_capacity == 60 {
inventory.arrow_capacity = 30;
}
}
_ => unreachable!(),
};
} else if dpad_right {
match unsafe { cursor } {
ORDON_SWORD_INDEX => {
inventory.ordon_sword_flag().activate();
... | Rust | 0 |
tion":
evaluator_list.append(ClassificationEvaluator(dataset_name, output_folder))
# Retrieval
if evaluator_type in ["retrieval"]:
evaluator_list.append(RetrievalEvaluator(dataset_name, output_folder, cfg['MODEL']['DECODER']['RETRIEVAL']['ENSEMBLE']))
if evaluator_type == "captioning":
... | Python | 1 |
PCLEAR_EN2R::NOGPREG
}
#[doc = "Checks if the value of the field is `CLRGPREG`"]
#[inline]
pub fn is_clrgpreg(&self) -> bool {
*self == GPCLEAR_EN2R::CLRGPREG
}
}
#[doc = "Possible values of the field `POL2`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum POL2R {
#[doc = "A channel 2... | Rust | 0 |
'c> Ast<'c> {
fn new(ctx: &'c Ctx, state: AstState<'c> ) -> Rc<Ast<'c>> {
let ast = Rc::new(Ast {
ctx: ctx,
state: state,
});
ast
}
}
impl <'c> Drop for Ast<'c> {
fn drop(&mut self) {
// println!("! dropping ast {:?}", self);
}
}
//////////////... | Rust | 0 |
ialize, Deserialize)]
#[serde(into = "String", try_from = "String")]
pub struct ChannelBitsBadgeUnlocks {
/// The channel_id to watch. Can be fetched with the [Get Users](crate::helix::users::get_users) endpoint
pub channel_id: u32,
}
impl_de_ser!(
ChannelBitsBadgeUnlocks,
"channel-bits-badge-... | Rust | 0 |
u8] = as_u8_slice(&data, data_length);
let data = unsafe { CStr::from_bytes_with_nul_unchecked(data) };
TagData {
vxid,
tag,
data,
ty,
}
}
pub(crate) fn read_next_record(&mut self) -> CursorResult {
match self.advance_next() {
... | Rust | 0 |
import os
import sys
import traceback
from ..operators.install_dependencies import load_dependencies
from ..utils import absolute_path
class Generator:
_instance = None
def __new__(cls):
if not cls._instance:
if not cls._instance:
cls._instance = super(Generator, cls).__n... | Python | 1 |
except subprocess.SubprocessError:
raise
except UserWarning:
raise
else:
raise RuntimeError("Only defined for nt and posix platforms")
def _kinit_with_keytab(principal: str, keytab: PathType) -> bool:
"""Kinit with keytab file"""
# test for valid tgt existence
l... | Python | 1 |
#!/usr/bin/python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
fh = open(sys.argv[-1], 'w')
for filename in sys.argv[1:-1]:
fh.write(open(filename).read())
fh.close()
| Python | 1 |
his should handle 50k+ blocks smoothly!")
# Test new batched rendering (should be MUCH faster)
print("\n1. Testing batched rendering...")
fig_batched = quick_preview(cap3d_file, max_blocks=50000)
print("✓ Batched rendering complete!")
# Test interactive dashboard
print("\n2. Creating i... | Python | 1 |
mmary Length: {len(new_summary)} characters")
logger.info(f"Improvement: {len(new_summary) - len(old_summary):+d} characters")
logger.info(f"\nOLD Full Text: {old_full_text_length} characters")
logger.info(f"NEW Full Text: {len(stored_full_text)} characters")
logger.info(... | Python | 1 |
nt-type", "application/vnd.schemaregistry.v1+json")
.with_body(&get_json_body_with_reference(
json_test_ref_schema(),
5,
json_get_result_references(),
))
.create();
let _m = mock("GET", "/subjects/result.json/versions/1")
... | Rust | 0 |
#Tunjangan Jabatan
gaji_pokok = 300000
golongan_1 = 0.05
golongan_2 = 0.1
golongan_3 = 0.15
#Tunjangan Pendidikan
pdk_SMA = 0.025
pdk_D1 = 0.05
pdk_D3 = 0.2
pdk_S1 = 0.3
#Jam Kerja
jam_normal = 8
#hitung tunjangan jabatan
per_jam_lebih = 3500
nama_karyawan = input("Nama Karyawan : ")
golongan = input("Golongan [1/2... | Python | 1 |
VNDB sent unknown command"),
}
}
}
impl std::error::Error for ResponseParseError {}
<reponame>fifth-postulate/mancala<filename>examples/node_count.rs<gh_stars>1-10
extern crate mancala;
use mancala::strategy::{MinMax, Strategy};
use mancala::game::Position;
fn main() {
for bowls in 1..4 {
for... | Rust | 0 |
gorithm=self.jwt_algorithm)
def _create_missing_claims_token(self) -> str:
"""創建缺少必要聲明的 JWT Token"""
payload = {
"user_id": "test_user",
# 缺少 username, role, exp 等聲明
"iat": int(datetime.now().timestamp()),
}
return jwt.encode(payload, self.jwt_sec... | Python | 1 |
"#,
)
.file("src/lib.rs", "")
.file("src/main.rs", "fn main() {}")
.file("tests/t1.rs", "")
.file("examples/ex1.rs", "fn main() {}")
.build();
p.cargo("build --all-targets -Ztimings")
.masquerade_as_nightly_cargo()
.with_stderr_unordered(
... | Rust | 0 |
ut(self.desc as *mut VirtIOVirtqueueDesc, self.queue_num)
};
let head = self.free_head;
let mut prev = 0;
let mut cur = self.free_head;
for i in 0..output.len() {
desc[cur].flags.write(VirtIOVirtqueueFlag::NEXT.bits());
desc[cur]
.addr
... | Rust | 0 |
rray(np_B)
hcl_C = hcl.asarray(np_C)
hcl_D = hcl.asarray(np_D)
mod.modules[0](hcl_A, hcl_B, hcl_C)
mod.modules[1](hcl_B, hcl_C, hcl_D)
print(hcl_D.asnumpy())
def test_module_mixed_paradigm():
hcl.init()
def algorithm(a, b, c):
@hcl.def_([a.shape, b.shape, c.shape])
def add... | Python | 1 |
!(line);
// Collect non-empty tokens separated by arbitrary \t or spaces
// but ignore the rest of the line if we encounter a #
let tokens = SPACE_TAB_RE.split(line_str.trim())
.take_while(|&s| !s.starts_with("#"))
.filter(|&s| !s.is_empty())
.collect::<Vec<&str>>();
// Skip blank li... | Rust | 0 |
;
# compute orientation of the contact from the surface normal:
# ~ phase_data = pb.phaseData[pid+1] # +1 because the for loop start at id = 1
phase_data = pb.phaseData[pid] # +1 because the for loop start at id = 1
# ~ n = normal_from_ineq(phase_data.S[ph... | Python | 1 |
time.sleep(2)
try:
j = http_json("GET", f"{endpoint}/v1/jobs/{job_id}", headers=headers, timeout=60)
except Exception as e:
print(f" poll error: {e}")
if time.time() - start > args.timeout:
a... | Python | 1 |
conf.z3_exe = Some(z3_exe);
}
if let Some(cvc4_exe) = toml_conf.cvc4_exe {
conf.cvc4_exe = Some(cvc4_exe);
}
}
// cmd
if let Some(boogie_exe) = self.boogie_exe.take() {
conf.boogie_exe = Some(boogie_exe);
}
... | Rust | 0 |
n = int(input())
if n <= 99:
print(130-n)
elif n <= 199:
print(200-n)
elif n <= 299:
print(300-n)
| Python | 1 |
D','O','E','O','D','V','E','O','D','V','E','V',
'D','V','E','O','M','O','E','O','D','O','E','O','D',
'O','E','O','D','O','E','O','E','O','D','V','E','V',
'D','O','E','O','D','O','E','V','D','V','E','O','D',
'V','E','O','D','O','E','O','D','V','E','O','D','O',
'E','O','D','O'... | Python | 1 |
: u32 = unsafe { std::mem::transmute(val) };
((bits >> 23) & 0xff) as i16
}
fn get_sign_f32(val: f32) -> bool {
let bits: u32 = unsafe { std::mem::transmute(val) };
((bits >> 31) & 0x1) != 0
}
fn get_sign_f64(val: f64) -> bool {
let bits: u64 = unsafe { std::mem::transmute(val) };
((bits >> 63) & ... | Rust | 0 |
Raydium::RAYUSDT => String::from("RAY-USDT"),
Raydium::RAYUSDC => String::from("RAY-USDC"),
Raydium::RAYSRM => String::from("RAY-SRM"),
Raydium::RAYSOL => String::from("RAY-SOL"),
Raydium::RAYETH => String::from("RAY-ETH"),
Raydium::ROPEUSDC => String:... | Rust | 0 |
import torch
#from torch.utils.data import DataLoader
from torch_geometric.data import DataLoader
from featerize_smiles import SmilesDataset
from transformers import AutoModelForCausalLM, AutoTokenizer
from torch import nn
import pandas as pd
from torch_geometric.nn import GCNConv
import numpy as np
from torch_geometri... | Python | 1 |
_serializing_if = "String::is_empty")]
pub description: String,
/// Group direct members count
#[serde(default, skip_serializing_if = "String::is_empty", rename = "directMembersCount")]
pub direct_members_count: String,
/// Email of group
#[serde(default, skip_serializing_if = "String::is_empty"... | Rust | 0 |
,
silva_var: p.silva_var,
silva_euclidean: p.silva_euclidean,
}
}
}
impl UIPointData {
pub fn ui_string(&self, attribute_names: Vec<String>) -> String {
// Add the first line, index and coords.
let mut res = format!("Index: {}", self.index);
res.push_str(... | Rust | 0 |
from __future__ import annotations
import logging
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
from packaging.utils import canonicalize_name
from poetry.core.packages.dependency import Dependency
from poetry.core.packages.directory_dependency import DirectoryDependency
from poetr... | Python | 1 |
shared state bot...");
//!
//! let bot = Bot::from_env().auto_send();
//!
//! let handler = Update::filter_message().branch(dptree::endpoint(
//! |msg: Message, bot: AutoSend<Bot>| async move {
//! let previous = MESSAGES_TOTAL.fetch_add(1, Ordering::Relaxed);
//! bot.send_message(msg.chat.id, forma... | Rust | 0 |
def test_load_euler_ancestral_from_pndm(self):
logger = logging.get_logger('diffusers.configuration_utils')
logger.setLevel(30)
with CaptureLogger(logger) as cap_logger:
euler = EulerAncestralDiscreteScheduler.from_pretrained(
'hf-internal-testing/tiny-stable-diffusion-torch', subfolder=... | Python | 1 |
tringExtension for crate::Device {}
/// <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VK_GOOGLE_display_timing.html>
pub trait GoogleDisplayTimingExtension: DeviceV1_0 {
/// The metadata for this extension.
#[allow(deprecated)]
const METADATA: Extension = GOOGLE_DISPLAY_TIMING_EXTE... | Rust | 0 |
_A::DIS)
}
#[doc = "FNCSEL = 0x3 - Output is push-pull"]
#[inline(always)]
pub fn pushpull(self) -> &'a mut W {
self.variant(GPIO26OUTCFG_A::PUSHPULL)
}
#[doc = "FNCSEL = 0x3 - Output is open drain"]
#[inline(always)]
pub fn od(self) -> &'a mut W {
self.variant(GPIO26OUTC... | Rust | 0 |
pub type NDIV_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `NDIV`"]
pub struct NDIV_W<'a> {
w: &'a mut W,
}
impl<'a> NDIV_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x7f << 8)) | (((... | Rust | 0 |
query_states,
key_states,
value_states,
# attn_bias=attention_mask,
attn_bias=xformers.ops.LowerTriangularMask(),
)
if attn_output.size() != (bsz, q_len, self.num_heads, self.head_dim):
raise ValueError(
f"`attn_output` should be o... | Python | 1 |
= 4
precision, recall, f1_score = calculate_detection_accuracy(true_positives, false_positives, false_negatives)
total_precision += precision
total_recall += recall
total_f1_score += f1_score
print("Original Image:")
cv2_imshow(image)
print("Result Image:")
cv2_imshow(result_image)
... | Python | 1 |
.\n"
"Cannot export text transcription file associated with an audio or video as a linked file."))
self.pushButton_export_attributes.setToolTip(_translate("Dialog_manage_files", "<html><head/><body><p>Export attributes to file</p></body></html>"))
self.pushButton_help.setToolTip(_translate("Dialog_manag... | Python | 1 |
headers=self.headers,
json=data)
response = raw_response.json()
except Exception as err:
print('Request Error:{}'.format(err))
time.sleep(3)
continue
... | Python | 1 |
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.tools import TavilySearchResults
def search_tool(query: str):
tool = TavilySearchResults(
max_results=5,
search_depth="advanced",
include_answer=True,
include_raw_content=True,
include_images=True
... | Python | 1 |
("action", "mint")
.add_attribute("minter", info.sender))
}
pub fn execute_update_traits(
deps: DepsMut,
_env: Env,
info: MessageInfo,
token_id: String,
exp: u64,
gold: u64,
stamina: u64,
) -> Result<Response, ContractError> {
let config = CONFIG.load(deps.storage)?;
let sta... | Rust | 0 |
from env import APP_URL
BASE = {
"welcome": "Привет!\n/help - помощь",
"help": f"""Бот создан для настольной игры GlichMe!
Для запуска необходимо перейти на <a href="{APP_URL}">сайт</a>, создать лобби и перейти по QR-коду.""",
}
ADVANCED = {
"connected": "{name}, вы успешно подключились к игре {game_id}!"... | Python | 1 |
_as_cell(&ptr).to_string());
}
_ => {}
}
}
}
Ok(DecompiledInstruction {
op: schema.name,
operands,
values,
})
} else {
Err(InvalidBy... | Rust | 0 |
authenticated encryption algorithm
A256cbcHs512,
}
impl AescbcHmacJweEncryption {
fn cipher(&self) -> Cipher {
match self {
Self::A128cbcHs256 => Cipher::aes_128_cbc(),
Self::A192cbcHs384 => Cipher::aes_192_cbc(),
Self::A256cbcHs512 => Cipher::aes_256_cbc(),
... | Rust | 0 |
with 0.5 being a square wave).
pub fn pulse<F: Into<Wave>, D: Into<Wave>>(freq: F, duty: D) -> Wave {
Wave::new(Box::new(PulseWave::new(freq.into(), duty.into())))
}
/// Creates a sine wave, with an amplitude of 1, whose frequency over time
/// is controlled by the input waveform (which may be ... | Rust | 0 |
Returns: iterable generator of tuple(neighbour, moving_cost)
neighbour(bi-tuple): a position near to the node.
moving_cost(float): the cost the agent has to pay to move from node to neighbour.
"""
directions = [[1, 0, 1], [0, 1, 1], [-1, 0, 1], [0, -1, 1],
... | Python | 1 |
ndom number generator, record buffer and config.
///
/// NOTE: The record buffer should be sized to fit an encrypted TLS record and the TLS handshake
/// record. The maximum value of a TLS record is 16 kB, which should be a safe value to use.
pub fn new(rng: RNG, record_buf: &'a mut [u8]) -> Self {
... | Rust | 0 |
:expr) => {
String::from(from_utf8($e).expect("Invalid UTF-8 sequence").trim())
};
}
fn get_wsl() -> String {
if env::consts::OS == "windows" {
return String::from("wsl");
}
return String::from("wsl");
}
fn main() {
let args: Vec<String> = env::args().collect();
let force_enable... | Rust | 0 |
mode='bilinear',
align_corners=self.align_corners)
fpn_outs = torch.cat(fpn_outs, dim=1)
x = self.fpn_bottleneck(fpn_outs)
# print('x:', x.size())
mu = self.mu(x)
# print('mu:', mu.size())
logvar = self.logvar(x)
# print('logvar:', ... | Python | 1 |
Service().validate_template_syntax(objective_template.name)
@router.post(
"/{objective_template_uid}/pre-instances",
dependencies=[security, rbac.LIBRARY_WRITE],
summary="Create a Pre-Instance",
status_code=201,
responses={
403: _generic_descriptions.ERROR_403,
201: {
... | Python | 1 |
from scattertext.termranking import AbsoluteFrequencyRanker
from scattertext.util import inherits_from
from scattertext.termscoring.RankDifference import RankDifference
class MultiCategoryAssociationBase:
def __init__(
self,
corpus,
use_metadata=False,
non_text=Fa... | Python | 1 |
:Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ths_data_ints](index.html) module"]
pub struct THS_DATA_INTS_SPEC;
impl crate::RegisterSpec for THS_DATA_INTS_SPEC {
type Ux = u32;
}
#[doc = "`read()` ... | Rust | 0 |
.borders(Borders::ALL),
// )
.state(&app.logs.state)
}
fn draw_context<B: Backend>(f: &mut Frame<B>, app: &App, area: Rect) {
let context = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
.split(area... | Rust | 0 |
weather data container from dict 't'
wdc = WeatherDataContainer(**rec)
# add wdc to dictionary for thisdate
self._store_WeatherDataContainer(wdc, wdc.DAY)
def _process_POWER_records(self, powerdata):
"""Process the meteorological records returned by NASA POWER
... | Python | 1 |
[u8; 6],
src: &[u8; 6],
ethertype: u16,
payload: Tail<'l>,
) -> Fragment<'l> {
let mut f = Fragment::from_tail(payload);
f.push_bytes(dst);
f.push_bytes(src);
f.push_be16(ethertype);
f
}
fn new_ipv4<'l>(
src: &net::Ipv4Addr,
sr... | Rust | 0 |
pmcounter31h,
__read_hpmcounter31h,
__write_hpmcounter31h
);
// Copyright 2016 The RLS Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// ... | Rust | 0 |
_name("ensure")
.help("Runs additional check to verify duplicate.")
.short("E")
.long("ensure"),
)
.arg(
Arg::with_name("verbose")
.help("Show extra logging")
.short("v")
.long("verbose"),
... | Rust | 0 |
wtLoginMiddleware<S>
where
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
{
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
type Error = Error;
type Future = Either<S::Future, FutureResult<Self::Response, Self::Error>>;
... | Rust | 0 |
#!/usr/bin/env python3
'''Test of freeze-thaw feature'''
from dnstest.test import Test
import threading
t = Test(tsig=False)
master = t.server("knot", xdp_enable=False) # DDNS over XDP not supported
slave = t.server("knot")
zone = t.zone("example.", storage=".")
t.link(zone, master, slave)
def sleep_alt(time1, op... | Python | 1 |
ter forcused form changed. Focused form id: {focused_form_id}')
# it isn't snapshot. It is just setting start position on foucsed form
if not focused_form_id in self._form_snapshots:
for aspect_name, aspect_selector in self._aspect_selectors.it... | Python | 1 |
println!("a: {:?}, b: {:?}", a, b);
}
}
/// # 函数:泛型函数
///
/// Base usage: 泛型函数可推断类型
///
/// ```rust
/// use std::ops::Mul;
/// fn square<T: Mul<T, Output=T>>(x: T, y: T) -> T {
/// x * y
/// }
/// fn main() {
/// let a: i32 = square(37, 41);
/// let b: f64 = square(37.2, 41.1);
/// assert_eq!(... | Rust | 0 |
entire_ underlying packet buffer - not just
/// the length of the current range.
///
/// This method is used when handing the `qSupported` packet in order to
/// obtain the maximum packet size the stub supports.
pub fn full_len(&self) -> usize {
self.buf.len()
}
}
impl<'a> Packet<'a> {
... | Rust | 0 |
return Err(ErrorKind::UnexpectedToken(lexer.token_as_str().to_owned(), field_type.to_owned()))?
};
token = Some(type_);
lexer.consume();
}
Ok(token.ok_or_else(|| ErrorKind::NonExistentType)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parser() {
let parser = Parser::new();
let ... | Rust | 0 |
);
indices.push(res_0 + 1);
indices.push(res_1);
indices.push(res_1 + 1);
indices.push(res_0 + 1);
}
// Calculate back face indices if back face is enabled.
// Two sided
for x in 0..tessellation_width * pla... | Rust | 0 |
)
else:
print(model , end=" ")
try:
price_no_discount = locate_element_with_retry(By.CSS_SELECTOR, '[data-testid="price-no-discount"]') #driver.find_element(By.CSS_SELECTOR , '[data-testid="price-no-discount"]')
if "line-t... | Python | 1 |
t form.
"""
return "[%s]" % (self._str_base())
@require_all_args
def assert_complete(self):
pass
@require_all_args
def vrange(self):
"""
Yields v_steps+1 SymPy numbers ranging from
v_min to v_max.
"""
d = (self.v_max - self.v_min) / self.... | Python | 1 |
_string()].
///
/// # Returns
///
/// A [`Identity`][crate::Identity] or [`None`]
/// if `error` is set. Free with `g_object_unref()`.
#[doc(alias = "polkit_identity_from_string")]
pub fn from_string(str: &str) -> Result<Option<Identity>, glib::Error> {
unsafe {
let mut e... | Rust | 0 |
])
-> Option<FunctionParam<'s>>
{
let attr: Option<Attribute> = if self.current_token().token_inner == TokenInner::SymHash {
let hash_token: Token<'s> = self.consume_token();
Some(self.parse_attribute(hash_token, false, failsafe_set)?)
} else {
None
... | Rust | 0 |
}
}
}
pub struct Text<'a> {
w: u32,
h: u32,
glyphs: Vec<rusttype::PositionedGlyph<'a>>
}
impl<'a> Text<'a> {
/// Return width of the text
pub fn width(&self) -> u32 {
self.w
}
/// Return height of the text
pub fn height(&self) -> u32 {
self.h
}
///... | Rust | 0 |
st.doc = self.doc.as_ptr() as _;
}
dst.get = Some(self.meth);
}
}
impl PySetterDef {
/// Define a setter.
pub fn new(name: &'static str, setter: ffi::setter, doc: &'static str) -> Self {
Self {
name: get_name(name),
meth: setter,
doc: get_doc(doc)... | Rust | 0 |
{repoResult['name']} by {repoOrgName}")
packagesQueryURI = f"https://artifacthub.io/api/v1/packages/search?limit=60&facets=false&kind=0&repo={repoResult['name']}"
response = requests.get(packagesQueryURI, headers=headers)
chartPackages = response.json()
... | Python | 1 |
config(dict): replaced config
"""
if options is not None:
for opt in options:
assert isinstance(opt, str), "option({}) should be a str".format(opt)
assert "=" in opt, "option({}) should contain a =" "to distinguish between key and value".format(opt)
pair = opt.sp... | Python | 1 |
# siem_dashboard_tool.py
"""
SIEM Dashboard Tool - Mini ELK Stack Clone for Security Event Monitoring
"""
from flask import Flask, render_template, jsonify, request
import random
import datetime
app = Flask(__name__)
# Simulated event logs
event_logs = [
{"timestamp": str(datetime.datetime.now()), "source": "Fire... | Python | 1 |
correct += 1;
if submission.e == submission.question.e_is_correct:
correct += 1;
if submission.f == submission.question.f_is_correct:
correct += 1;
# If all choices have been correctly selected, then give full credit.
... | Python | 1 |
onizing
between workers. It is called by update_with_local_losses from all
ranks with identical arguments. Thus, it should have deterministic
behavior to maintain state across workers.
:param ts: a list of int timesteps.
:param losses: a list of float losses, one per timestep.
... | 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 |
(x2)
if get_feature:
return feature
x5 = self.resblocks(feature)
out = self.conditional_res(x5, condition)
#print(x2.size())
#print(x5.size())
output4 = self.asm(x2, out,condition)
h = output4
# n, _,h,w = out.size()
# attr =... | Python | 1 |
# -*- coding: utf-8 -*-
''' Trivial test for QuadLoadedArea objects.'''
from __future__ import print_function
__author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AOO)"
__copyright__= "Copyright 2022, LCPT and AOO"
__license__= "GPL"
__version__= "3.0"
__email__= "l.pereztato@gmail.com"
import geom
import math
fro... | Python | 1 |
import numpy as np
import scipy
import time
def predict(net, label_colors, threshold, image=None):
num_classes = len(label_colors)
if image is not None:
image = image.transpose((2, 0, 1))
net.blobs['data'].data[0] = image
start = time.time()
net.forward()
print('Prediction time',... | Python | 1 |
er_night.txt:5:But I beseech your grace that I may know",
"midsummer_night.txt:6:The worst that may befall me in this case,",
"paradise_lost.txt:2:Of that Forbidden Tree, whose mortal tast",
"paradise_lost.txt:6:Sing Heav'nly Muse, that on the secret top"
]
));
set_up_test_case!(#[test]
#[i... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.