text string | label_name string | labels int64 |
|---|---|---|
impl crate::video::DenseOpticalFlowConst for PtrOfFarnebackOpticalFlow {
#[inline] fn as_raw_DenseOpticalFlow(&self) -> *const c_void { self.inner_as_raw() }
}
impl crate::video::DenseOpticalFlow for PtrOfFarnebackOpticalFlow {
#[inline] fn as_raw_mut_DenseOpticalFlow(&mut self) -> *mut c_void { self.inner_as_r... | Rust | 0 |
import os
# Ignor qilinadigan papka va fayl kengaytmalari
IGNORED_DIRS = {"__pycache__"}
IGNORED_EXTENSIONS = {".pyc", ".pyo", ".log", ".tmp"}
def save_clean_structure(root_dir, output_file="structure.txt"):
with open(output_file, "w", encoding="utf-8") as f:
for foldername, subfolders, filenames in os.wa... | Python | 1 |
# -*- coding: utf-8 -*-
"""Provide log symbols for various log levels."""
import platform
from enum import Enum
from colorama import init, deinit, Fore
init(autoreset=True)
_MAIN = {
'info': 'ℹ',
'success': '✔',
'warning': '⚠',
'error': '✖'
}
_FALLBACKS = {
'info': '¡',
'success': 'v',
'... | Python | 1 |
t_physical_device_surface_formats(
&self,
physical_device: vk::PhysicalDevice,
surface: vk::SurfaceKHR,
) -> VkResult<Vec<vk::SurfaceFormatKHR>> {
let mut count = 0;
self.surface_fn.get_physical_device_surface_formats_khr(
physical_device,
surface,
... | Rust | 0 |
_path => value_spec_replicas_path = Some(serde::de::MapAccess::next_value(&mut map)?),
Field::Key_status_replicas_path => value_status_replicas_path = Some(serde::de::MapAccess::next_value(&mut map)?),
Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess:... | Rust | 0 |
def main(args, device):
print('loading data.')
vocab, c2i, i2c, _, _ = get_vocab_from_file(args.i + '/vocab.txt')
model = CharRNN(len(vocab), len(vocab), max_len=args.maxlen).to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
pt = torch.load(args.logdir + '/' + args.model, map_loc... | Python | 1 |
name="orgName")
def org_name(self) -> _builtins.str:
"""
The name of the organization that is associated with the certificate.
"""
return pulumi.get(self, "org_name")
@_builtins.property
@pulumi.getter
def province(self) -> _builtins.str:
"""
The province... | Python | 1 |
| size as usize),
is_raw: raw_format,
context_owned: true,
_phantom_data: PhantomData,
}
}
fn from_result(
proc_name: &'static str,
result: c_int,
context: *mut c_char,
raw_format: bool,
) -> Result<Self> {
if result == -1 ... | Rust | 0 |
_speaker_gain(Gain(1));
assert!(exec.run_until_stalled(&mut speaker_gain_fut).is_pending());
// reporting a new value will finally complete the hanging get
ctrl.report_speaker_gain(Gain(2));
let result = exec.run_until_stalled(&mut speaker_gain_fut).expect("future to complete");
... | Rust | 0 |
ckWriteGuard<'a, Model> {
model.as_ref().unwrap().write().unwrap()
}
unsafe fn read_model<'a>(model: native::Model) -> RwLockReadGuard<'a, Model> {
model.as_ref().unwrap().read().unwrap()
}
fn tunet_model_start_impl(
val: usize,
main: native::MainCallback,
data: *mut c_void,
) -> Result<i32> {
... | Rust | 0 |
r=initializer):
mtest = PTBModel(is_training=False, config=eval_config,
input_=test_input)
# Corresponding official documents about supervisor:
# https://www.tensorflow.org/programmers_guide/supervisor
sv = tf.train.Supervisor(logdir=FLAGS.save_p... | Python | 1 |
# -*- coding: utf-8 -*-
u"""
Created on 2015-8-14
@author: cheng.li
"""
from PyFin.DateUtilities import Date
from PyFin.Utilities import require
class SettingsFactory(object):
def __init__(self):
self._evaluationDate = None
self._includeToday = None
@property
def evaluationDate(self):
... | Python | 1 |
子商户的商户号,由微信支付生成并下发。示例值:'1900000109'
"""
params = {}
if not guide_id:
raise Exception('guide_id is not assigned.')
path = '/v3/smartguide/guides/%s' % guide_id
cipher_data = False
if name:
params.update({'name': self._core.encrypt(name)})
cipher_data = True
if mobile:
... | Python | 1 |
or en if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple co... | Python | 1 |
Vec<T>> {
let strs = match matches.values_of_lossy(name) {
None => return Ok(default),
Some(strs) => strs,
};
let mut values = vec![];
for s in strs {
values.push(s.parse()?);
}
Ok(values)
}
/// Return a prettily formatted error, including its entire causal chain.
fn pre... | Rust | 0 |
raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the ... | Rust | 0 |
(&mut self) -> Option<&mut VecDeque<<P as KeyVal>::Key>> {
match *self {
KVStoreCommand::Find(ref mut qm,_,_) => qm.get_filter_mut(),
_ => None,
}
}
fn adjust_lastsent_next_hop(&mut self, nbquery : usize) {
match *self {
KVStoreCommand::Find(ref mut qm,_,_) => qm.adjust_lastsent_next_... | Rust | 0 |
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_acce... | Rust | 0 |
import unittest
from general_data_structures.tree.tree_node import TreeNode
class MyTestCase(unittest.TestCase):
def test_tree_node_creation(self):
node_1: TreeNode[str] = TreeNode("node_1")
node_2: TreeNode[int] = TreeNode(7)
self.assertEqual("node_1", node_1.value)
self.assertE... | Python | 1 |
"""Sine Message, by Al Sweigart al@inventwithpython.com
Create a sine-wavy message.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: tiny, artistic"""
import math, shutil, sys, time
# Get the size of the terminal window:
WIDTH, HEIGHT = shutil.get_terminal_size()
# We can't print... | Python | 1 |
from re import finditer
with open('txt/24_6798.txt') as file:
st = file.readline()
pattern = r'([CDF][ACDFO][AO])+'
res = [i.group() for i in finditer(pattern, st)]
print(len(max(res, key=len)))
| Python | 1 |
import numpy as np
import tensorflow as tf
wordVectors = np.load('./training_data/wordVectors.npy')
print ('Loaded the word vectors!')
maxSeqLength = 250
batchSize = 32
numDimensions=50
ids = np.load('./training_data/idsMatrix.npy')
from random import randint
def getTrainBatch():
labels = []
arr = np.zeros([... | Python | 1 |
pub unsafe extern "C" fn mz_inflateInit2(stream: *mut mz_stream, window_bits: c_int) -> c_int {
libz_sys::inflateInit2_(
stream,
window_bits,
ZLIB_VERSION.as_ptr() as *const c_char,
mem::size_of::<mz_stream>() as c_int,
)
}
}
/// Cloudflare optimized ... | Rust | 0 |
sert_matches("Some(${a:kind(literal)})", code, &["Some(42)", "Some(\"foo\")", "Some(true)"]);
assert_matches("Some(${a:not(kind(literal))})", code, &["Some(x1)", "Some(40 + 2)"]);
}
#[test]
fn match_reordered_struct_instantiation() {
assert_matches(
"Foo {aa: 1, b: 2, ccc: 3}",
"struct Foo {} f... | Rust | 0 |
import operator_benchmark as op_bench
import torch
"""Microbenchmarks for quantized groupnorm operator."""
groupnorm_configs_short = op_bench.cross_product_configs(
dims=(
(32, 8, 16),
(32, 8, 56, 56),
),
num_groups=(2, 4),
dtype=(torch.qint8,),
tags=["short"],
)
class QGroupNo... | Python | 1 |
mpare = []
# Stat fields per term
for independent_variable_name in independent_variables_names:
stats_variable = [ anova_table[independent_variable_name][header] for header in column_headers]
stats_main.append(stats_variable)
# Residual fields
for header in column_headers:
stat... | Python | 1 |
Screen,
/// A specific media type.
Custom(String),
}
impl MediaType {
fn parse(name: &str) -> Result<Self, ()> {
match_ignore_ascii_case! { &*name,
"all" => Ok(MediaType::All),
"print" => Ok(MediaType::Print),
"screen" => Ok(MediaType::Screen),
_ => Ok(MediaType::Custom(name.into()))
... | Rust | 0 |
match_str = match captures.0.get(i + 1) {
Some(m) => m.as_str(),
None => return Err(pars::MatchError::MissingCaptureGroup(i)),
};
let match_idx = position_mapping[i];
ordered_matches[match_idx] = match_str;
}
};
Ok(re_block)
}
fn gene... | Rust | 0 |
ng to their start times.
*
* Example 1:
*
* Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
* Output: [[1,5],[6,9]]
* Example 2:
*
* Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
* Output: [[1,2],[3,10],[12,16]]
* Explanation: Because the new interval [4,8] overlaps with [3,... | Rust | 0 |
# Работа с данными модуль shelve
import shelve
with shelve.open("shelve_test") as cars:
cars["opel"] = "Germany"
cars["ford"] = "USA"
cars["mazda"] = "Japan"
cars["renault"] = "France"
#print(cars["ford"])
#print(cars["renault"])
#print(cars["mazda"])
#print(cars["opel"])
#cars["... | Python | 1 |
)
)]
ContractId(ContractId),
/// RGB Contract genesis raw data
///
/// HRP: `genesis`
#[from]
#[cfg_attr(
feature = "serde",
serde(
serialize_with = "to_bech32_str",
deserialize_with = "from_bech32_str"
)
)]
Genesis(Genesis),
/// ... | Rust | 0 |
, 25.0);
}
#[test]
fn vector3_sub() {
let lhs = Vector3::new(1.0, 22.0, 33.0);
let rhs = Vector3::new(11.0, 15.0, 22.0);
let res = lhs - rhs;
assert_eq!(res.x, -10.0);
assert_eq!(res.y, 7.0);
assert_eq!(res.z, 11.0);
}
#[test]
fn vector3_assign_sub() {
let mut lhs = Vector3::new(1.0, 22.0... | Rust | 0 |
import json
import asyncio
from database import get_conversation_data, get_action_logs
from query_base import process_query
from consulting_base import process_consulting
from qa_base import process_qa
from humanity_base import process_humanity
from process_manager import process_manager
async def process_all_flows(qu... | Python | 1 |
# cc program
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets, uic
from PyQt5.QtCore import *
import requests
from bs4 import BeautifulSoup
from requests.models import ContentDecodingError
def getVal(cont1, cont2):
cont1val = cont1.split("-")[1]
co... | Python | 1 |
Statistic(
name=f"number_of_{self.name}",
unit=MetricStatisticsType.COUNT.unit,
value=0,
type=MetricStatisticsType.COUNT,
),
Statistic(
name=f"{self.name}_fail_rate_below_threshold",... | Python | 1 |
ref_datum: "W84",
}),
};
let expected_output = Ok(("", expected_sentence));
assert_eq!(expected_output, parse_sentence(input));
}
#[test]
fn test_parse_dtm_lat_lon_alt() {
let input = "$GPDTM,999,,0.08,N,0.07,E,-47.7,W84*1B\r\n";
let expected_sent... | Rust | 0 |
"""
SQL Database configuration and models
Uses PostgreSQL for structured data
"""
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
import os
from backend.utils.config import settings
# ... | Python | 1 |
('Wrong ID')}")
print(f"Look up patron: {library.lookup_patron_from_id('Wrong ID')}")
print(f"Test: Check out and return items")
library.check_out_library_item("Patron ID", "Book ID")
library.check_out_library_item("Patron 2 ID", "Album ID")
library.check_out_library_item("Patro... | Python | 1 |
source_id
}
/// For content which does not have a source file **use with caution**
pub const fn new_null() -> Self {
Self(0)
}
pub const fn is_null(&self) -> bool {
self.0 == 0
}
/// Note that this does clone the result
pub fn get_file(&self) -> Option<(PathBu... | Rust | 0 |
=> Some(LIGHT_GRAY),
2 => Some(DARK_GRAY),
3 => Some(BLACK),
_ => Some(RED)
}
}
}
fn get_bg_color(&self, value: u8, palette_num: u8) -> Color {
if self.color_mode {
let to_8_bit_color = |c: u8| (c << 3) | (c >> 2);
... | Rust | 0 |
rs) method.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ScriptRedeemer {
/// Hash of the transaction.
pub tx_hash: String,
/// The index of the redeemer pointer in the transaction.
pub tx_index: Integer,
/// Validation purpose.
pub purpose: PurposeType,
/// The budget in Memor... | Rust | 0 |
DodgerBluet,
/// Specifies a color with RGB value (178,34,34)
#[strum(serialize = "firebrick")]
Firebrick,
/// Specifies a color with RGB value (255,250,240)
#[strum(serialize = "floralWhite")]
FloralWhite,
/// Specifies a color with RGB value (34,139,34)
#[strum(serialize = "forestG... | Rust | 0 |
"vopf;" => "\u{1D567}",
"vprop;" => "\u{0221D}",
"vrtri;" => "\u{022B3}",
"Vscr;" => "\u{1D4B1}",
"vscr;" => "\u{1D4CB}",
"vsubnE;" => "\u{02ACB}\u{0FE00}",
"vsubne;" => "\u{0228A}\u{0FE00}",
"vsupnE;" => "\u{02ACC}\u{0FE00}",
"vsupne;" => "\u{0228B}\u{0F... | Rust | 0 |
#
# Copyright 2020 Apple Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | Python | 1 |
)
# 绘制湍流强度分布直方图
plt.subplot(2, 2, 2)
if min_len > 0:
plt.hist(
model_c_sample['turbulence_intensity'],
bins=30,
alpha=0.5,
label='模型C'
)
plt.hist(
model_d_sample['turbu... | Python | 1 |
xf5\xe00^~\xfb\xda<y\xf9\xda]}\
{\x97]k\xbb!\xd0\xad\xb9\xbf\x08\xf5\xfdz\xca7\
XV\xcd\xa0\xd3f\x89\xd7(\xbc3\xcc\xa6\xd3x\xbb\
\x19\xed\xb6\x8en\xad\x8e\xaeZ\xfb\x8a\xcd*z\xeaz\
\xd3\xb7\x07\xe0\xcd\x80\xb5\x02\x89\x0d\xbd\x19\xba.\xdb\xb7\
m\xb88\xf4\xe1\xc9~\x1a\x9f4\xd3\xf4\x04\xa4{\xd1\
:\xed\xd2\x13w\xc8\x84\xfa2... | Python | 1 |
device: ep_proxy_client,
}]),
inherit_parent_launch_services: Some(false),
logger_options: Some(LoggerOptions {
enabled: Some(true),
klogs_enabled: Some(false),
filter_options: None,
syslog_output: None,
..LoggerOptions::EMPTY
... | Rust | 0 |
n<u64> {
Self::to_f32(*self).to_u64()
}
#[inline]
fn to_i8(&self) -> Option<i8> {
Self::to_f32(*self).to_i8()
}
#[inline]
fn to_u8(&self) -> Option<u8> {
Self::to_f32(*self).to_u8()
}
#[inline]
fn to_i16(&self) -> Option<i16> {
Self::to_f32(*self).to_i... | Rust | 0 |
class.
/// The constructor receives bytes from a string.
pub fn new(bytes: &[u8]) -> Result<Self, AnyException> {
let import_object = imports! {};
Ok(Self {
instance: Rc::new(runtime::instantiate(bytes, &import_object).map_err(|e| {
AnyException::new(
... | Rust | 0 |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import sys
sys.path.append('../scripts/')
from mcl import *
# In[3]:
class ResetMcl(Mcl): ###ermcl sensor_reset_mclから改造
def __init__(self, envmap, init_pose, num, motion_noise_stds={"nn":0.19, "no":0.001, "on":0.13, "oo":0.2}, distance_dev_rate... | Python | 1 |
import json
from circuits.core import Event
META_EXCLUDE = set(dir(Event()))
META_EXCLUDE.add('node_call_id')
META_EXCLUDE.add('node_sock')
META_EXCLUDE.add('node_without_result')
META_EXCLUDE.add('success_channels')
def load_event(s):
data = json.loads(s)
name = data['name']
args = []
for arg in... | Python | 1 |
// Set index
self.table.set_chunk_for_index(idx, address)?;
// Write
self.table.write_bytes(address, bytes)?;
Some(())
})
}
}
<reponame>flier/bitflags<filename>test_suite/tests/compile-fail/private_flags.rs<gh_stars>1-10
#[macro_use]
ex... | Rust | 0 |
nt2<i32>;
type IntoIter = NeiborNodesIter;
// note that into_iter() is consuming self
fn into_iter(self) -> Self::IntoIter {
Self::IntoIter {
iter: self.neibs.into_iter(),
}
}
}
struct NeiborNodesIter {
iter: IntoIter<Point2<i32>>,
}
impl<'a> Iterator for NeiborNodesIt... | Rust | 0 |
or if the CY flag is set, 6 is added to the most significant 4 bits of the accumulator.
0x28 => "0x28: -",
0x29 => "0x29: DAD H",
// Adds HI to HL.
0x2A => "0x2a: LHLD addr",
// Load H & L direct
// The content of the memory location, whose address is specified in byte 2... | Rust | 0 |
en from default arg
set_seed(args.seed)
# Prints (and logs) all parameters for the experiment
print_command_line_arguments(args, args_dict, log_file_name, args.epochs)
# Get pretrain loaders
# (IF APPLICABLE) Data augmentation happens in this function
trainloader, valloader, testloade... | Python | 1 |
from collections import deque
import sys
input = sys.stdin.readline
row, col, k = map(int, input().split())
graph = [[0] * col for _ in range(row)]
for _ in range(k):
x1, y1, x2, y2 = map(int, input().split())
for r in range(y1, y2):
for c in range(x1, x2):
graph[r][c] += 1
# 상 하 좌 우
dx = [0, 0, -1, ... | Python | 1 |
I(CGI),
#[asn(key = 0, extended = true)]
TargetgNgRanNode_ID(TargetNgRanNode_ID),
}
#[derive(Debug, AperCodec)]
#[asn(type = "SEQUENCE", extensible = true, optional_fields = 1)]
pub struct TargetNgRanNode_ID {
pub global_ran_node_id: Global_RAN_NODE_ID,
pub selected_tai: FiveGSTAI,
#[asn(optional_i... | Rust | 0 |
xB297_ED46),
(r"meshes\x\ex_velothi_hilltent_01.nif", 0x203B_1656, 0x0D31_6670),
(r"meshes\x\ex_velothi_entrance_03.nif", 0x203B_1656, 0x218F_7DB4),
(r"meshes\x\ex_velothi_entrance_01.nif", 0x203B_1656, 0x218F_7DB5),
(r"meshes\x\ex_velothi_entrance_02.nif", 0x203B_1656, 0xA18F_7DB4),
(r"meshes\... | Rust | 0 |
width = "32")]
pub u: [u32; 7],
}
use std::path::Path;
use crate::image_map;
use crate::text::{FontFamily, FontId};
use crate::widget::Widget;
pub trait TWindow {
fn add_font_family(&mut self, family: FontFamily) -> String;
fn add_font<P: AsRef<Path>>(&mut self, path: P) -> FontId;
fn add_image_from_p... | Rust | 0 |
>(elems: E) -> N {
elems
.map(N::abs)
.max_by(N::total_cmp)
.unwrap_or_else(N::zero)
}
fn next_guess<N: Number + Float + Any, I: Infinitesimal<N>>(
dim: Dim,
guess: &mut Vec<N>,
result: &[Jet<N, I>],
) -> bool {
let mut neg_f_x0_data = Vec::with_capacity(dim.0);
let mut ... | Rust | 0 |
lista = [1,3,4,-2,-3,5,21,-17] | Python | 1 |
'''Imports CIFAR-10 data.'''
import numpy as np
import pickle
import sys
def load_CIFAR10_batch(filename):
'''load data from single CIFAR-10 file'''
with open(filename, 'rb') as f:
if sys.version_info[0] < 3:
dict = pickle.load(f)
else:
dict = pickle.load(f, encoding='latin1')
x = dict['d... | Python | 1 |
# region Map Classes
class MCow_Map_SceneObjectsFound:
def __init__(self):
self.meshes = []
self.waters = []
self.lavas = []
self.lights = []
self.locators = []
self.triggers = []
self.particles = []
self.collisions = [[] for i in range(10)] # Each co... | Python | 1 |
import numpy as np
import json
def convert_vec2angle31(n1):
"""
Inputs:
n1 = numpy array with shape (3,1)
"""
assert n1.shape == (3,1)
n1 = n1/np.linalg.norm(n1)
n1_x, n1_y, n1_z_abs = n1[0,0], n1[1,0], np.abs(n1[2,0])
# x-augulation
if n1_x > 0:
x_angle = n... | Python | 1 |
def __init__(self, n_vars, nf, target_window, head_dropout=0):
super().__init__()
self.n_vars = n_vars
self.linears = nn.ModuleList()
self.dropouts = nn.ModuleList()
self.flattens = nn.ModuleList()
for i in range(self.n_vars):
self.flattens.append(nn.Flatten(s... | Python | 1 |
command.stdout(Stdio::null());
command.stderr(Stdio::null());
}
let process = command.spawn()?;
// Open pipes. Panic if we cannot connect after a timeout.
let (to_guest, from_guest) = panic_on_timeout(
move || (File::create(to_guest_pipe), File::open(from_... | Rust | 0 |
model::{
gateway::Ready
},
prelude::{
EventHandler,
Context
},
framework::standard::{
StandardFramework,
macros::group
}
};
use std::{
fs,
process,
collections::HashSet
};
mod commands;
use commands::{
abilityinfo::*,
common::*
};
... | Rust | 0 |
es")
ser_to_ser_pandas_udf_example(spark)
print("Running pandas_udf example: Iterator of Series to Iterator of Series")
iter_ser_to_iter_ser_pandas_udf_example(spark)
print("Running pandas_udf example: Iterator of Multiple Series to Iterator of Series")
iter_sers_to_iter_ser_pandas_udf_example(spark... | Python | 1 |
let (renderer, mut input) = winit::init(log.clone()).map_err(|err| {
slog::crit!(log, "Failed to initialize Winit backend: {}", err);
})?;
#[cfg(feature = "egl")]
let egl_buffer_reader = Rc::new(RefCell::new(
if let Ok(egl_buffer_reader) = renderer.bind_wl_display(&display.borrow()) {
... | Rust | 0 |
ngles,
20,
lmbda=lmbda,
lmbda_red=lambdared,
verbose=verbose,
Quameasopts=qualmeas,
computel2=True,
)
# OS-SART
# ========================================================================
# Additionally OS-SART includes a couple of other parameters, related to
# the subsets.
#
# 'blocksize': ... | Python | 1 |
Type::Path(type_path) if type_path.qself.is_none() && path_is_option(&type_path.path) => {
// Get the first segment of the path (there is only one, in fact: "Option"):
let type_params = &type_path.path.segments.first().unwrap().arguments;
// It should have only on angle-bracketed par... | Rust | 0 |
lback_wallet()?;
return res;
}
Ok(_) => {
update_wallet()?;
}
}
} else {
panic!("dest not in expected format: {}", dest);
}
Ok(())
}
/// Builds a transaction to send to someone from the HD seed associated with the
/// wallet and the amount to send. Handles reading through the wallet data file,
... | Rust | 0 |
"""
Utility functions for AI Studio Deep Learning Templates.
This module contains common functions used across notebooks in the project,
including configuration loading, model initialization, and other utilities.
"""
import os
import yaml
from pathlib import Path
from typing import Dict, Any, Optional
def load_conf... | Python | 1 |
fault_results_logger(self, x, y2, o, stats):
for sentence_idx, s in enumerate(x):
expected_tags = y2[sentence_idx]
predicted_tags = o[sentence_idx]
correct = True
for idx, tag in enumerate(expected_tags):
if (predicted_tags[idx] != tag and correct)... | Python | 1 |
id, id.connector, e),
}
}
}
}
}
}
}
displays
}
/// Updates the display info with data retrieved from the device's
/// reported capabilities.
pub fn update... | Rust | 0 |
y-daw-core
// Some modified code from baseplug:
//
// https://github.com/wrl/baseplug/blob/trunk/src/parameter.rs
// https://github.com/wrl/baseplug/blob/trunk/LICENSE-APACHE
// https://github.com/wrl/baseplug/blob/trunk/LICENSE-MIT
//
// Thanks wrl! :)
use std::sync::Arc;
use super::atomic::{AtomicF32, AtomicF64};
... | Rust | 0 |
() == "" {
println!("please input the valid name");
continue;
} else {
break;
}
};
println!("Please input the department name");
loop {
io::stdin().read_line(&mut department).expect("please input the department... | Rust | 0 |
n_access!(u.0, 0, self.num_nodes, self.inner.right_sib, NodeId)
}
/// Obtain the list of samples for the current tree/tree sequence
/// as a vector.
#[deprecated(since = "0.2.3", note = "Please use Tree::sample_nodes instead")]
pub fn samples_to_vec(&self) -> Vec<NodeId> {
let num_samples =... | Rust | 0 |
', np.dtype(np.object_))], align=True))
dtype_map.setdefault(Institution, np.dtype([('name', np.dtype(np.object_)), ('address', np.dtype(np.object_))], align=True))
dtype_map.setdefault(ExamInformation, np.dtype([('subject', get_dtype(Subject)), ('institution', get_dtype(Institution)), ('protocol', np.dtype([('... | Python | 1 |
EVs and the Pokemon's nature). The complete formula can be
/// found [here (HP)][1] and [here (other stats)][2].
///
/// [1]: http://bulbapedia.bulbagarden.net/wiki/File:HPStatCalcGen34.png
/// [2]: http://bulbapedia.bulbagarden.net/wiki/File:OtherStatCalcGen34.png
pub fn at_level(base: Self, level... | Rust | 0 |
this will be read later on
// when it's time to remove this element and its closures and event listeners
element
.set_attribute(DATA_SAURON_VDOM_ID, &unique_id.to_string())
.expect("Could not set attribute on element");
closures.insert(unique_id, vec... | Rust | 0 |
import hashlib
import hmac
import string
import time
from django_otp_keygen.utils import (
get_otp_format,
get_otp_generation_interval,
get_otp_length,
)
class OTP:
"""Base OTP Class"""
def __init__(
self,
key: str,
):
self.key = key
self.length = get_otp_leng... | Python | 1 |
/// # Examples
///
/// ```
/// # use adventofcode::solution::
/// # {
/// # y2020::D6Pt1 as Solution,
/// # Solution as S,
/// # };
/// # env_logger::init();
/// let input = "abc\n\
/// \n\
/// a\n\
/// b\n\
/// c\n\
/// \n\
/// ab\n\
/// ac\n\
/// \n\
/// a\n\
/// a\n\
... | Rust | 0 |
print(x)
# You can use the keys() method to return the keys of a dictionary:
for x in thisdict.keys():
print(x)
# Loop through both keys and values, by using the items() method:
for x, y in thisdict.items():
print(f"{x} : {y}")
# Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": ... | Python | 1 |
MAX = 999999
# DP 배열 및 징검다리 정보 초기화
d = [[MAX, MAX] for _ in range(21)]
v = [(0, 0) for _ in range(21)]
# 입력 받기
n = int(input())
for i in range(1, n):
v1, v2 = map(int, input().split())
v[i] = (v1, v2)
k = int(input())
# 초기 상태 설정
d[1][0] = 0
if n > 1:
d[2][0] = v[1][0]
if n > 2:
d[3][0] = min(v[1][0]... | Python | 1 |
# src/greenkube/storage/base_repository.py
from abc import ABC, abstractmethod
class CarbonIntensityRepository(ABC):
"""
Interface définissant le contrat pour le stockage et la récupération
des données d'intensité carbone.
"""
@abstractmethod
def get_latest_for_zone(self, zone: str) -> float | ... | Python | 1 |
#!/usr/bin/env python3
# encoding: utf-8
from tests.utils import *
def test_keep_hardlinks(usual_setup_usual_teardown):
create_file('xxx', 'file_a')
create_link('file_a', 'file_b')
create_file('xxx', 'file_z')
head, *data, footer = run_rmlint('--no-hardlinked -S a')
assert data[0]["path"].endswit... | Python | 1 |
import json
from datetime import datetime
def load_bookings():
try:
with open("bookings.json", "r") as file:
return json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
return []
def save_booking(movie_name, showtime, seat, hall, bookings):
booking_time = datetime.... | Python | 1 |
ctionBuilder::default()
.inputs(
inputs
.into_iter()
.map(|(txid, index)| CellInput::new(OutPoint::new(txid.to_owned(), index), 0)),
)
.set_header_deps(header_deps)
.outputs((0..outputs_len).map(|i| {
CellOutput::new_builder()
... | Rust | 0 |
)
@patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock)
def test_listening_process_canceled_on_cancel_exception(self, ws_connect_mock):
messages = asyncio.Queue()
ws_connect_mock.side_effect = asyncio.CancelledError
with self.assertRaises(asyncio.CancelledError):
... | Python | 1 |
#!/usr/bin/env python
# coding: utf-8
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import pandas as pd
import numpy as np
import time
import argparse
from tools.EarlyStopping import EarlyStopping
from sklearn.metrics import mean_squared_error, r2_score
from scipy.stats import pear... | Python | 1 |
en",
corpus: data::SUBTITLE_EN_TEENY,
never: &[
Query { name: "john-watson", needle: "<NAME>", count: 0 },
Query { name: "all-common-bytes", needle: "sternness", count: 0 },
Query { name: "some-rare-bytes", needle: "quartz", count: 0 },
Query { name: "two-... | Rust | 0 |
erOperators.plus {
result += second_float;
} else if operator == pconsts::ParserOperators.minus {
result -= second_float;
} else if operator == pconsts::ParserOperators.multiply {
result *= second_float;... | Rust | 0 |
if name.startswith(sympy_symbol_prefix):
name = name[len(sympy_symbol_prefix) :]
args = [from_sympy(arg) for arg in expr.args]
builtin = sympy_to_mathics.get(name)
if builtin is not None:
return builtin.from_sympy(tuple(args))
return Expression(Symbol(na... | Python | 1 |
('-b', '--border', action='store_true', help='Apply Watershed Technique.')
parser.add_argument('-ga', '--gaussian', action='store_true', help='Apply Gaussian filter.')
parser.add_argument('-co', '--contrast', action='store_true', help='Apply Constrast filter.')
parser.add_argument('-sh', '--sharpness', acti... | Python | 1 |
ON_CONTINUE_SEARCH
}
let (handler, f) = match HANDLER.with(|x| x.get()) {
Some(handler) => handler,
None => return 0, // EXCEPTION_CONTINUE_SEARCH
};
let sp;
cfg_if::cfg_if! {
if #[cfg(target_arch = "x86_64")] ... | Rust | 0 |
'1.10000'}
),
# .. raises ValueError because GTD required gtdTime
(req.TakeProfitDetails,
{"price": 1.10,
"timeInForce": OD.TimeInForce.GTD},
{'timeInForce': 'GTD',
'price': '1.10000'},
ValueError
),
# .. raises ValueError bec... | Python | 1 |
condition_results.append(tmp_rule)
for i in range(len(condition_results)):
combined_condition = combined_condition.replace(f'rule{i+1}', f'condition_results[{i}]')
# Replace logical operators
combi... | Python | 1 |
from django.urls import path
from . import views
urlpatterns = [
path('find-grid/', views.find_wrs2_grid, name='find_wrs2_grid'),
] | Python | 1 |
import tkinter as tk
class SemafaroGUI:
def __init__(self, master):
self.master = master
self.master.title("Semáforo")
self.master.geometry("200x400")
self.cor_vermelha = tk.Canvas(master, width=100, height=100, bg="black")
self.cor_vermelha.create_oval(10, 10, 90, 90, fill... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.