text string | label_name string | labels int64 |
|---|---|---|
REMOVES:");
for block in removes.iter() {
println!(" - {:?}", block);
}
}
tx.exec(&mut program, added_blocks, removes);
let end_ns = time::precise_time_ns()... | Rust | 0 |
nt Queue. When there are no requests to process, block until one arrives.
extern "C" fn spi_task_func(_arg: Ptr) {
loop {
// Forever read SPI requests and execute them. Will call spi_event_callback().
os::eventq_run(
unsafe { &mut SPI_EVENT_QUEUE }
).expect("eventq fail");
... | Rust | 0 |
/ Converts an `ast::Path` to `Path`. Works with use trees.
/// It correctly handles `$crate` based path from macro call.
pub(super) fn lower_path(mut path: ast::Path, hygiene: &Hygiene) -> Option<Path> {
let mut kind = PathKind::Plain;
let mut type_anchor = None;
let mut segments = Vec::new();
let mut g... | Rust | 0 |
trize("dtype", LOADABLE_UNSUPPORTED_FEATURE_DTYPES)
def test_trees_loadable_unsupported_dtype(dtype):
"""Should raise error during convert()"""
X, Y = datasets.make_classification(n_classes=10, n_features=10,
n_informative=8, n_samples=100, random_state=1)
estimator = RandomForestClassifier(n_estim... | Python | 1 |
import pprint
import random
import re
import requests
def chooseWord(options):
chances = 0
for weight in options.values(): chances += weight
roll = random.random() # number between 0 and 1
for word, chance in options.items():
roll -= (chance / chances)
if roll <= 0: return word
return array(options.keys()... | Python | 1 |
self.mom_phases = []
for i, (start, lambda_func) in enumerate(mom_phases):
if len(self.mom_phases) != 0:
assert self.mom_phases[-1][0] < start
if isinstance(lambda_func, str):
lambda_func = eval(lambda_func)
if i < len(mom_phases) - 1:
... | Python | 1 |
),
(Pos::make_none(), "__xhpAttributeDeclaration".into()),
)),
vec![],
vec![],
None,
)),
)];
for xua in xual.iter() {
match xua.1.as_happly() {
Some((ast_defs::Id(_, s), hints)) if hints.is_empty() => {
... | Rust | 0 |
LOCK>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PWRLOCK;
#[doc = "`read()` method returns [pwrlock::R](pwrlock::R) reader structure"]
impl crate::Readable for PWRLOCK {}
#[doc = "`write(|w| ..)` method takes [pwrlock::W](pwrlock::W) writer structure"]
impl crate::Writable for PWRLOCK {}
#[doc = "Regulator and ... | Rust | 0 |
b
);
}
#[test]
fn test_projective_to_affine() {
let a = G2Projective::generator();
let b = G2Projective::identity();
assert!(bool::from(G2Affine::from(a).is_on_curve()));
assert!(!bool::from(G2Affine::from(a).is_identity()));
assert!(bool::from(G2Affine::from(b).is_on_curve()));
asser... | Rust | 0 |
brushes = [
("DELETE", "Delete", 'MESH_CIRCLE'),
("CONNECT", "Connect", 'DRIVER_DISTANCE'),
("MERGE", "Merge", 'META_DATA'),
("EXTEND", "Extend", 'TRACKING_FORWARDS'),
("MOVE", "Move", 'TRIA_RIGHT'),
... | Python | 1 |
from unittest.mock import patch
from calculate_age import age_calculator
@patch("time.time", return_value=1621848668.0)
def test_age_calculator(mock_time):
"""
Test the age_calculator function
Mocks the current time and check if the age is calculated
based on current time
"""
name = "Chloe"
... | Python | 1 |
0. `[]` The mint for this account
/// 1. `[writable]` The source account.
/// 2. `[writable]` The destination account.
/// 3. '[]' The source account's multisignature owner/delegate.
/// 4. ..3+M '[signer]' M signer accounts.
Transfer2 {
/// The amount of tokens to transfer.
... | Rust | 0 |
video_title else "Unknown Title"] = video_url
return title, videos
return None, None
except Exception as e:
logging.error(f"Error retrieving videos: {e}")
return None, None
def save_to_file(videos, name):
"""
Saves video titles and URLs to a .txt file.
If a t... | Python | 1 |
impl Display for Str {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
/// Wrapper for `llvm::Str`s that LLVM gave us ownership of.
///
/// The LLVM C API sometimes returns strings that we have to `free`, so we wrap
/// them with this at 0 cost.
pub struct Stri... | Rust | 0 |
def selection_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i+1, len(arr)):
if arr[min_index] > arr[j]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
# Test the function
arr = [5, 3, 10, 9, 1]
print(selection_sort(arr)) | Python | 1 |
ted_funds_entry() -> MigratedFundsEntry {
MigratedFundsEntry::from(
&bee::option::MigratedFundsEntry::new(
bee::option::TailTransactionHash::new(TAIL_TRANSACTION_HASH2).unwrap(),
bee_block_stardust::address::Address::Alias(bee_test::rand::address::rand_alias_address()... | Rust | 0 |
Felt::ZERO];
mem.write(addr2, value5);
assert_eq!(value5, mem.get_value(addr2.as_int()).unwrap());
assert_eq!(2, mem.size());
assert_eq!(2, mem.trace_len());
// write a value into address 1; clk = 3
mem.advance_clock();
let addr1 = Felt::new(1);
let value7 = [Felt::new(7), Felt::ZERO, ... | Rust | 0 |
for cross builds explicitly
if "_PYTHON_HOST_PLATFORM" in os.environ:
return os.environ["_PYTHON_HOST_PLATFORM"]
# Try to distinguish various flavours of Unix
osname, host, release, version, machine = os.uname()
# Convert the OS name to lowercase, remove '/' characters, and translate
# spa... | Python | 1 |
NSDefaultRunLoopMode,
false);
NSApp().sendEvent_(event);
self.poll_events()
}
}
pub unsafe fn make_current(&self) {
self.context.makeCurrentContext();
}
pub fn get_proc_address(&self, _addr: &str) -> *const () {
let symbol_name: CFString... | Rust | 0 |
n)
print "Min,mean,max: %f, %f, %f" % (data_mag_ma_mean.min(), data_mag_ma_mean.mean(), data_mag_ma_mean.max())
if options.max_decim is None:
assert((new_length % options.max_length) == 0)
decim_max = new_length / options.max_length
else:
decim_max = options.max_decim
print "Max decim:", decim_max
#new_len... | Python | 1 |
e for PadPresence {
unsafe fn set_value(value: &mut Value, this: &Self) {
gobject_ffi::g_value_set_enum(value.to_glib_none_mut().0, this.to_glib())
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum PadProbeReturn {
Drop,
Ok,
Remove,
Pass,
Handled,
#[doc(hidden)]
... | Rust | 0 |
(self, TP):
"""Return a ChemicalVolumetricFlowIndexer that references this object's molar data.
Parameters
----------
TP : ThermalCondition
"""
try:
vol = self._data_cache['vol']
except:
chemicals = self._chemicals
V = [i.V for i in chemicals]
dct = ... | Python | 1 |
et the point size
fn set_point_size(&mut self, size: f32) {
self.current_render_mode_mut().set_point_size(size);
}
/// Reset the point size back to its initial value
fn reset_point_size(&mut self) {
self.current_render_mode_mut().reset_point_size();
}
/// Get the current point ... | Rust | 0 |
next_node_index += 1
executor.shutdown(wait=True)
else:
for cluster in clusters:
process_cluster(
cluster,
new_level_nodes,
next_node_index,
summarization... | Python | 1 |
# this is a simple joke bot
# it will ask the user what they want?
# if they say joke, it will tell them a joke
PROMPT = input("\033[34mWhat do yo want?")
JOKE = " Sophia is heading out to the grocery store. A programmer tells her: get a liter of milk, and if they have eggs, get 12. Sophia returns with 13 liters of m... | Python | 1 |
syncio.sleep(flood_time)
except:
continue
text += _["broad_7"].format(num, sent)
try:
await aw.edit_text(text)
except:
pass
IS_BROADCASTING = False
async def auto_clean():
while not await asyncio.sleep(10):
try:
... | Python | 1 |
obalIndex) -> GlobalDesc {
GlobalDesc(unsafe { baldrapi::env_global(self.env, global_index) })
}
pub fn min_memory_length(&self) -> i64 {
self.env.min_memory_length as i64
}
}
use ssbh_data::anim_data::GroupType;
use ssbh_data::matl_data::{
BlendFactor, CullMode, FillMode, MagFilter, Max... | Rust | 0 |
def __init__(self, args):
super().__init__(args)
self.latent_dim = args.vae_latent_dim
self.input_dropout = nn.Dropout(p=args.vae_dropout)
dims = [args.vae_hidden_dim] * 2 * args.vae_num_hidden
dims = [args.num_items] + dims + [args.vae_latent_dim * 2]
encoder_modules, decoder_modules = [], []
... | Python | 1 |
ath.isdir(args.in_path)
for sd_fname in glob.glob(os.path.join(args.in_path, '*')):
new_sds.append(get_pickle(sd_fname))
for sd in new_sds:
if merged_sd is None:
merged_sd = copy.deepcopy(sd)
else:
m... | Python | 1 |
}
}
verified_txs.push(verified_tx);
}
let (new_forest, new_catchup) = work_forest.normalize(&utxo_hasher);
let utxoroot = new_forest.root(&utxo_hasher);
// Check the utxo set commitment
if block_header.utxoroot != utxoroot {
... | Rust | 0 |
from typing import Hashable, List
import numpy as np
from scipy.stats import boxcox, boxcox_llf
## Python versions of R's match() function
# For each element of 'a', returns indices in 'b' that match a, or None if no match
def match_list(a: List[Hashable], b: List[Hashable]) -> List[int]:
return [b.index(x) if... | Python | 1 |
nt!(", {}", self.values[p].value());
pointer = p;
}
print!("]\n");
}
/// Print the first n elements of the circular list - starting from the current pointer
pub fn printn(&self, n: usize) {
if self.pointer.is_none() {
return;
}
let mut pointe... | Rust | 0 |
a
0c @ s6 d dl mZ d dlmZ er&d dlT ndZd dlT dS ) )absolute_import)PY3)*TN)
__future__r Zfuture.utilsr reprlibZ__future_module__repr r r i/home/tom/ab/renpy-build-fix/tmp/install.linux-x86_64/lib/python3.9/site-packages/future/moves/reprlib.py<m... | Python | 1 |
import tensorflow as tf
import os
from sklearn import datasets
import matplotlib.pyplot as plt
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
print("\n##iris dataset load: datasets.load_iris")
data = datasets.load_iris()
#print(data.DESCR)
#print(dir(data))
#print(data.data)
#print(data.feature_names)
#print(data.target)... | Python | 1 |
data_f4[i] = clamp(data_f4[i], -1.f, 1.f);
}
}
float time = end(index);
rsDebug("fp_clamp4 M ops", 100.f / time);
}
void fp_mad_test(uint32_t index, int test_num) {
int x;
for (x=0; x < 1025; x++) {
data_f1[x] = (x & 0xf) * 0.1f;
data_f4[x].x = (x & 0xf) * 0.1f... | Rust | 0 |
branch) = parsed
.get_base58_branch()
.expect("couldn't encode branch to base58");
assert_eq!(&branch[..len], BRANCH_BASE58.as_bytes());
let ops = parsed.mut_ops();
let op1 = ops
.parse_next()
.expect("failed to parse operation")
.expe... | Rust | 0 |
table name][description]\n[String][Integer][Decimal]\n[][][]\n[prop1][prop2][prop3]\n";
let s = format!("{}{}", pre_string, "");
let err = TableSchema::schema_from_qvs20_str(&s).unwrap_err();
assert_eq!(
remove_src_loc(err),
"Error: Missing mandatory Schema 5th row - colu... | Rust | 0 |
ange(p).end()))
.unwrap_or(p.cur_tok().range.start);
if !p.typescript() {
let err = p
.err_builder("type annotations can only be used in TypeScript files")
.primary(start..end, "");
p.error(err);
}
if p.typescript() && for_stmt {
let err = p
.err_builder("`for` statement declarators canno... | Rust | 0 |
_key: PathBuf,
}
<gh_stars>0
use crate::support::registry::{self, alt_api_path, Package};
use crate::support::{basic_manifest, paths, project};
use std::fs::File;
use std::io::Write;
#[test]
fn is_feature_gated() {
let p = project()
.file(
"Cargo.toml",
r#"
[project]
... | Rust | 0 |
ns[qid][0])
else:
num_no_question += 1
print '%d answers with buzzes' % len(buzz_ans)
print '%d questions with buzzes does not have training data' % num_no_question
# collect content model and buzz model data
content_ans_qids = defaultdict(list)
buzz_ans_qids = defaultdict(list)... | Python | 1 |
_LayerId(self.as_raw_mut_Net(), layer.as_raw_mut_DictValue()) }.into_result()
}
/// Connects output of the first layer to input of the second layer.
/// ## Parameters
/// * outPin: descriptor of the first layer output.
/// * inpPin: descriptor of the second layer input.
///
/// Descriptors have the following ... | Rust | 0 |
from django.contrib import admin
from core.models import *
admin.site.register(Pets)
admin.site.register(Parent)
admin.site.register(MedicalHistory)
admin.site.register(CustomUser)
| Python | 1 |
t min = sorted[0].1;
let min_group = sorted
.into_iter()
.group_by(|a| a.1 == min)
.map(|(_, v)| v)
.next()
.unwrap();
rng.choose1(&min_group).0.clone()
}
}
fn random_neighbor<T, R>(adjacency_matrix: &LinearMap<T, Vec<T>>, rng: &mut R) -> ... | Rust | 0 |
True),
'WA': state(state_abbrv='WA', elect_votes=12, reg_voters=5016000, voter_turn_out=0.738, vote_prob_dem=vote_prob, vote_prob_repub=vote_prob, party = party, exclude_odd_vote_results = True),
'WV': state(state_abbrv='WV', elect_votes=4, reg_voters=1255000, voter_turn_out=0.550, vote_prob_dem=vote_prob, vote... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(-10,10,0.001)
y1=np.sin(x)
y2=np.cos(x)
plt.plot(x,y1,x,y2)
plt.title("sine curve and cosine curve")
plt.xlabel("Values of x")
plt.ylabel("Values of sin(x) and cos(x)")
plt.grid()
plt.show() | Python | 1 |
e().overlap(&"x=3..7".to_range())
);
}
#[test]
fn test_range_overlaps_start() {
assert_eq!(
Some("x=3..4".to_range()),
"x=3..7".to_range().overlap(&"x=1..4".to_range())
);
}
#[test]
fn test_range_overlap_enclosing() {
assert_eq!(
... | Rust | 0 |
(0, True))
# Tests for interpolating_spline
def test_10_points_degree_1():
d = 1
X = [-5, 2, 3, 4, 7, 9, 10, 30, 31, 34]
Y = [-10, -2, 2, 4, 7, 6, 20, 45, 19, 25]
spline = interpolating_spline(d, x, X, Y)
assert spline == Piecewise((x*Rational(8, 7) - Rational(30, 7), (x >= -5) & (x <= 2)),... | Python | 1 |
desc, vwap, mvwap, roc")
.required(true)
.takes_value(true))
.arg(Arg::with_name("symbol")
.short("y")
.long("symbol")
.help("Stock symbol")
.required(true)
.takes_value(true))
... | Rust | 0 |
tick_count as u32) as usize;
debug!(
"Calibrated APIC Timer with a counter value of {} for a single tick of a {} Hz timer",
CALIBRATED_COUNTER_VALUE,
processor::TIMER_FREQUENCY
);
}
irq::enable();
}
pub fn set_oneshot_timer(wakeup_time: Option<usize>) {
if let Some(wt) = wakeup_time {
// Calculate t... | Rust | 0 |
ystimer_unit0_op: SYS_TIMER_SYSTIMER_UNIT0_OP,
#[doc = "0x08 - SYS_TIMER_SYSTIMER_UNIT1_OP"]
pub sys_timer_systimer_unit1_op: SYS_TIMER_SYSTIMER_UNIT1_OP,
#[doc = "0x0c - SYS_TIMER_SYSTIMER_UNIT0_LOAD_HI"]
pub sys_timer_systimer_unit0_load_hi: SYS_TIMER_SYSTIMER_UNIT0_LOAD_HI,
#[doc = "0x10 - SYS_TI... | Rust | 0 |
Nope>, MultiErrorInfo<Self::LW,Nope>,Self::P, Self::LW>>;
type REP = ReplyInfoProvider<
// SizedWindows<TestSizedWindows>,
// Full<ReplyTraits<P>>,
Self::P,
Self::SSW,
Self::SSR,
Self::SP,
>;
type SP = SProv;
type EP = MulErrorProvider;
}
#[derive(Clone)]
pub enum TestMode {
NoReply,
R... | Rust | 0 |
#[cfg(test)]
#[macro_use]
extern crate quickcheck_macros;
use num::integer::binomial;
use num::{Float, FromPrimitive};
/// Estimates the first $k$ moments of a distribution in an online fashion (either each datum being
/// incrementally added, or sets of data being added in batches). There is no need to use this
/// m... | Rust | 0 |
while True:
try:
m, n = map(int, input().split())
a = []
mx = 0
for i in range(m):
a.append(list(map(int, input().split())))
for i in range(1, m):
for j in range(n):
if a[i][j] == 1:
a[i][j] += a[i - 1][j]
fo... | Python | 1 |
# label shape (60000, 10)
# print('-' * 22 + "\n")
test_images = self.extract_images(test_images_path)
test_labels = self.extract_labels(test_labels_path)
# assert train_images.shape[0] == train_labels.shape[0]
# assert test_images.shape[0] == test_labels.shape[0]
#
... | Python | 1 |
Inst::xmm_rm_r_imm(SseOpcode::Roundpd, RegMem::reg(xmm15), w_xmm15, 0, false),
"66450F3A09FF00",
"roundpd $0, %xmm15, %xmm15",
));
// ========================================================
// Pertaining to atomics.
let am1: SyntheticAmode = Amode::imm_reg_reg_shift(321, r10, r... | Rust | 0 |
#!/usr/bin/python
# coding=utf-8
# <xbar.title>Huobi last price</xbar.title>
# <xbar.version>v1.0</xbar.version>
# <xbar.author>Sam Xie</xbar.author>
# <xbar.author.github>mountain3th</xbar.author.github>
# <xbar.desc>A very simple huobi last price display tool</xbar.desc>
# <xbar.dependencies>python</xbar.dependencie... | Python | 1 |
#!/usr/bin/python3
"""
Given a string S of '(' and ')' parentheses, we add the minimum number of
parentheses ( '(' or ')', and in any positions ) so that the resulting
parentheses string is valid.
Formally, a parentheses string is valid if and only if:
It is the empty string, or
It can be written as AB (A concatenate... | Python | 1 |
}
#[test]
fn test_generate_never_temporary_identifier_with_wilcard() {
for _i in 0..1_000_000 {
let generated = Ssn::generate();
let first_identifier = generated.chars().nth(7).unwrap();
assert_ne!(
first_identifier, '9',
"never g... | Rust | 0 |
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import os
# Carregar o modelo
model = tf.keras.models.load_model('cats_dogs_classifier.keras')
# Mostrar o resumo do modelo
print("\nEstrutura do Modelo:")
model.summary()
# Funรงรฃo para testar uma imagem
def testar_image... | Python | 1 |
ted,
#[msg("You havent finished your warm up period")]
StakingWarmupNotFinished,
#[msg("Attempting to use a staking counter going in the wrong direction")]
IncorrectStakingCounterType,
#[msg("Staking cooldown not finished")]
StakingCooldownNotFinished,
#[msg("Invalid program owner")]
Inv... | Rust | 0 |
:param duration: Default to None will display immediately.
Or it will display like a streaming subtitle in the duration.
"""
if not self.is_connected:
logger.warning("OBS client is not connected. This methods is called but nothing will happen.")
return
... | Python | 1 |
bound at all.
///
/// For example if a message was divided into 300 `Fragment`s (i.e. 2 `FragmentSet`s,
/// the structures might look as follows:
///
/// Set1: [f1 {id = 12345}, f2 {id = 12345}, ... f255 {id = 12345, next_id = 54321}]
/// Set2: [f1 {id = 54321, previous_id = 12345}, f2 {id = 54321}, ... f45 {id = 5432... | Rust | 0 |
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
from odoo.addons.mail.tools.discuss import Store
class MailThread(models.AbstractModel):
_inherit = 'mail.thread'
def _thread_to_store(self, store: Store, fields, *, request_list=None):
super()._thread... | Python | 1 |
changed_properties,
invalidated_properties: vec![],
};
properties_changed.to_emit_message(&adapter_path.into())
}
fn device_rssi_message(device_path: &'static str, rssi: i16) -> Message {
let mut changed_properties: HashMap<String, Variant<Box<dyn RefArg>>> = HashMap:... | Rust | 0 |
'''
A simple Program for grabing video from basler camera and converting it to opencv img.
Tested on Basler acA1300-200uc (USB3, linux 64bit , python 3.5)
'''
from pypylon import pylon
import cv2
# conecting to the first available camera
camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
... | Python | 1 |
al encoding
self.pe_hidden_size = configs.enc_in
if self.pe_hidden_size % 2 == 1:
self.pe_hidden_size += 1
num_timescales = self.pe_hidden_size // 2
max_timescale = 10000.0
min_timescale = 1.0
log_timescale_increment = (
math.log(float(max_ti... | Python | 1 |
ducts/", headers=headers)
print(f" Status: {response.status_code}")
if response.status_code == 200:
products = response.json()
print(f" Produtos encontrados: {len(products.get('items', []))}")
else:
print(f" Erro: {response.text}")
# Tes... | Python | 1 |
# 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 |
, n-1)).doit() == \
Piecewise((n*(n - 1)/2, Eq(x, y/(y + 1))),
(x*(y + 1)*(n*x*y*(x + x/y)**n/(x + x/y)
+ n*x*(x + x/y)**n/(x + x/y) - n*y*(x
+ x/y)**n/(x + x/y) - x*y*(x + x/y)**n/(x
+ x/y) - x*(x + x/y)**n/(x + x/y) + y)/(x*y
+ x - y)**2, True))
def test_issue_14112()... | Python | 1 |
def min_operations(n, s, themes):
# Check for the length
if len(s) != n or any(len(t) != n for t in themes):
return -1
# Check for lowercase English letters
if not all(c.islower() for c in s) or any(not all(c.islower() for c in t) for t in themes):
return -1
# Check for the cor... | Python | 1 |
let toolchain = std::option_env!("RUSTUP_TOOLCHAIN");
toolchain_path(home.map(String::from), toolchain.map(String::from))
});
tracing::debug!(?path, "Sysroot path.");
path
}
#[cfg(test)]
mod parser_test {
use super::*;
#[test]
fn test_rustc_version() {
let a... | Rust | 0 |
import tkinter as tk
win = tk.Tk()
win.geometry("300x260+100+200")
win['bg'] = "#33ffe6"
win.title("Calculator")
calc = tk.Entry(win,justify=tk.RIGHT, font=("Arial", 15))
calc.grid(row=0, column=0, columnspan=3, stick= "we")
def add_digit(digit):
value = calc.get() + str(digit)
calc.delete(0, tk.END)
calc... | Python | 1 |
from airflow import DAG
from airflow.operators.bash import BashOperator
from datetime import datetime, timedelta
default_args = {
'start_date': datetime(2019, 1, 1),
'owner': 'Airflow'
}
with DAG(dag_id='project_b', schedule_interval="0 0 * * *", default_args=default_args, catchup=False) as dag:
# T... | Python | 1 |
ity: usize,
tickets_generated: AtomicBool,
}
impl ParallelTable {
pub fn new(target_n: usize) -> Self {
let capacity = target_n + 1;
let mut shared_mem = vec![None; capacity];
shared_mem[0] = Some(BigInt::from(1));
shared_mem[1] = Some(BigInt::from(1));
Self {
... | Rust | 0 |
"""Network CDK construct module."""
from aws_cdk import aws_ec2 as ec2
from constructs import Construct
from cdk.cdk_goat_service.cdk_constructs.constants import ALLOWED_CIDR, VPC_CIDR
class NetworkConstruct(Construct):
"""Network CDK construct class."""
def __init__(self, scope: Construct, id: str, *, pref... | Python | 1 |
# Copyright (c) 2017 - 2019 Uber Technologies, Inc.
#
# Licensed under the Uber Non-Commercial License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at the root directory of this project.
#
# See the License for the specific language governing... | Python | 1 |
``rust
/// #[tokio::main]
/// async fn main() {
/// use chrono::NaiveDate;
/// use coingecko_rs::CoinGeckoClient;
/// let client = CoinGeckoClient::default();
///
/// let from = NaiveDate::from_ymd(2014, 2, 16).and_hms(19, 0, 32);
/// let to = NaiveDate::from_ymd(2015... | Rust | 0 |
rest;
}
return (true, input);
}
(false, bs)
}
}
}
fn run_any<F>(rules: &Rules, messages: &[Input], check: F) -> Output
where
F: for<'b> Fn(&Rules, &'b [u8]) -> (bool, &'b [u8]),
{
messages
.iter()
.map(|msg| {
let ... | Rust | 0 |
"""
this is an example enrichment plugin.
it processes every provided documents and adds a bunch of fields, including "enriched": true
"""
from typing import override
import muty.file
import muty.log
import muty.os
import muty.string
import muty.time
import muty.xml
from sqlalchemy.ext.asyncio import AsyncSession
from... | Python | 1 |
LF9-DF07U$B97JJ1D7WKP/HLIJLRKF1MFHJP7NVDEBU1J*Z222E.GJI77N IKXN9+6J5DG3VWU5ZXT$ZRWP7++KM5MMUN/7UTFEEZPBK8C 7KMBI.3ZDBDREY7IM*N1KS3UI$6JD.JKLKA3UBJM-SJ9:OHBURZEF50WAQ 3";
assert_eq!(expected, without_prefix);
}
#[test]
fn it_decodes_base45() {
let data = "NCFOXN%TS3DH3ZSUZK+.V0ETD%65NL-AH-R6... | Rust | 0 |
from . import _padlib_bezier
from . import _padlib_linepattern
from . import _padlib_rrect
from . import _padlib_spline
from . import _padlib_polygon
def bezier(surface, color, controlpointslist, steps, width=1):
_padlib_bezier.draw(surface, color, controlpointslist, steps, False, width, False)
def aabezier(surfac... | Python | 1 |
ng many important types.
pub use crate::extension::ExtensionDescriptor;
pub use crate::feature::{FeatureCache, FeatureCollection, MissingFeatureError, ThreadingClass};
pub use crate::match_extensions;
pub use crate::plugin::{
lv2_descriptors, Plugin, PluginInfo, PluginInstance, PluginInstanceDescriptor, PortCollect... | Rust | 0 |
core_pool = any(dev.path == d["device_path"]
for d in cas_devices_dict["core_pool"].values())
if not (should_be_in_core_pool ^ is_in_core_pool):
TestRun.LOGGER.info(f"Core device {dev.path} is"
f"{'' if should_be_in_core_pool else ' not'} listed in core ... | Python | 1 |
#python ็ปๆฑ็ถๅพๆ็บฟๅพ
#-*- coding: utf-8 -*-
import matplotlib.ticker as mtick
import matplotlib.pyplot as plt
import matplotlib
import os
import re
from utils.get_flops import get_flops
from scipy import signal
mode1 = {
"tick": 17,
"fig": [5, 4],
"legend": 17,
"label": 22
}
mode2 = {
"tick": 10,
... | Python | 1 |
11\n".as_bytes());
assert_eq!(eaglesong_builder_2.finalize(), HASH_34_1);
}
}
#![allow(unused_must_use)]
extern crate biscuit_auth as biscuit;
extern crate curve25519_dalek;
extern crate hex;
extern crate prost;
extern crate rand;
use biscuit::crypto::KeyPair;
use biscuit::error;
use biscuit::token::{build... | Rust | 0 |
import pyDOE
import numpy as np
# Uses Latin hypercube sampling to create a list of uniformly and randomly selected samples.
def lhsSampler(ranges, numSamples):
if numSamples == 0:
return []
paramSamples = pyDOE.lhs(len(ranges), samples=numSamples)
# Vectorize to make faster
normalizedSamples... | Python | 1 |
range_size.
/// Let l_p be the minimal integer such that range_size^l_p >= p,
/// witness[var_1], ..., witness[var_k] are guaranteed to be in [0,
/// range_size^l_p). Return error if any variables are invalid.
fn mod_add_internal(
&mut self,
vars: &[Variable],
p: F,
l_p:... | Rust | 0 |
# [03] START: FILE pages/10_admin_prompt.py โ wrapper to real admin prompt
from __future__ import annotations
import streamlit as st
# ๊ธฐ๋ณธ "Pages" ๋ค๋น ์์ ์จ๊น
st.markdown(
"""
<style>
[data-testid="stSidebarNav"],
section[data-testid="stSidebarNav"],
nav[data-testid="stSidebarNav"],
div[dat... | Python | 1 |
(43);
pub const E6: Square = Square(44);
pub const F6: Square = Square(45);
pub const G6: Square = Square(46);
pub const H6: Square = Square(47);
pub const A7: Square = Square(48);
pub const B7: Square = Square(49);
pub const C7: Square = Square(50);
pub const D7: Square = Square(51);
pub const E7: Square = Square(52);... | Rust | 0 |
ProxyMode::Disconnect => match stream.shutdown(Shutdown::Both) {
Ok(()) => {}
Err(_) => break,
},
}
match conn.write(&buffer[0..n]) {
Ok(_) =... | Rust | 0 |
from ._assertion_kind import AssertionKind # noqa: F401
from ._contract_assertion_label import (
ContractAssertionInfo, # noqa: F401
ContractAssertionLabel, # noqa: F401
)
from ._contract_violation import ContractViolation # noqa: F401
from ._contract_violation_exception import ContractViolationException #... | Python | 1 |
# -*- coding; utf-8 -*-
from .storageprotos_pb2 import SignedPreKeyRecordStructure
from ..ecc.curve import Curve
from ..ecc.eckeypair import ECKeyPair
class SignedPreKeyRecord:
def __init__(self, _id=None, timestamp=None, ecKeyPair=None, signature=None, serialized=None):
self.structure = SignedPreKeyReco... | Python | 1 |
})))),
case::pptp_sequence_missing_payload(
&[
// header: key and sequence flag set. Version 1 and no acknowledgement.
0x30, 0x01,
// protocol type: must be 0x880b for PPTP
0x88, 0x0b,
// key bytes (payload ... | Rust | 0 |
e destination",
conflicts_with("force_associate_bind_addr"),
display_order(1000)
)]
pub force_associate_dst: bool,
#[structopt(
long = "force-associate-bind-address",
help = "Force to associate with the replied bind address",
display_order(1001)
)]
pub force_a... | Rust | 0 |
pare("SELECT COUNT(*) FROM quotes")?
.query_row(params![], |row| row.get(0))
}
}
<reponame>ilianaw/safeword
//! An example of why you might want Safeword: dropping a UnixListener doesn't delete the socket,
//! and starting the application again causes an error because the address is already in use. Our
... | Rust | 0 |
chunk.encode3(CONS, 256, 256, 256, 1).unwrap();
chunk.encode3(CONS, 2, 256, 256, 1).unwrap();
chunk.encode3(CONS, 256, 1, 1, 1).unwrap();
chunk.encode3(CONS, 257, 257, 257, 1).unwrap();
chunk
.encode3(CONS, u16::MAX, u16::MAX, u16::MAX, 1)
.unwrap();
... | Rust | 0 |
from sqlmodel import SQLModel, Field
class ManufacturerBase(SQLModel):
name: str
class ManufacturerDb(ManufacturerBase):
id: int
class ManufacturerIn(ManufacturerBase):
pass
class ShoeBase(SQLModel):
model: str
manufacturer: str
class ShoeIn(ShoeBase):
pass
class ShoeDb(ShoeBase, tab... | Python | 1 |
import torch
from torch.nn import Module
import models.diffusion as diffusion
from models.diffusion import VarianceSchedule, D2MP_OB
import numpy as np
class D2MP(Module):
def __init__(self, config, encoder=None, device="cuda"):
super().__init__()
self.config = config
self.device = device
... | Python | 1 |
_point() {
let c: C192<P192, R192> = C192;
assert_eq!(c.G().is_valid(), true)
}
#[test]
fn reject_invalid_point() {
let c: C192<P192, R192> = C192;
let p = AffinePoint {
x: c.G().x,
y: FieldElem { limbs: c.G().y.limbs + One::one() }
};
... | Rust | 0 |
ot_order = self.get_rotation_order()
trans = bvh_motion[:, :3]
poses = R.from_euler(rot_order, bvh_motion[:, 3:].reshape((seq_len * num_joints, 3)), degrees=True)
poses = poses.as_matrix().reshape((seq_len, num_joints, 3, 3))
times = np.arange(seq_len, dtype=poses.dtype)
interp... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.