text string | label_name string | labels int64 |
|---|---|---|
led: {e}")
if not utxos:
cli.close(); raise SystemExit("no UTXOs for the derived address")
try:
raw_hex, txid_local, fee_atoms, change_atoms, size_bytes = build_and_sign(
priv, pub, utxos, dest_h160, int(args.amount_atoms), args.fee_per_byte, my_h160
)
except Exception a... | Python | 1 |
rope_scaling_js = RopeScalingArgs(
factor=rope_scaling["factor"],
low_freq_factor=rope_scaling["low_freq_factor"],
high_freq_factor=rope_scaling["high_freq_factor"],
original_max_position_embeddings=rope_scaling["original_max_position_embeddings"],
... | Python | 1 |
} else {
tcx.sess.delay_span_bug(span, &msg)
}
}
PatKind::Wild
}
}
// All other references are converted into deref patterns and then recursively
... | Rust | 0 |
o, frames=np.arange(0, poses[0].shape[0]), interval=0, repeat=True)
plt.draw()
def reload_poses():
nonlocal poses, action
if 'action' in all_poses:
action = all_poses.pop('action')
poses = all_poses
# for ax, title in zip(ax_3d, poses.keys()):
# ax.se... | Python | 1 |
return Ok(p);
}
pub mod extension;
pub mod conf;#[macro_use] extern crate serde_derive;
extern crate serde;
extern crate serde_json;
#[macro_use] extern crate jsonrpc_client_core;
extern crate jsonrpc_client_http;
extern crate hyper;
use jsonrpc_client_http::HttpTransport;
use hyper::header::{Authorization, Basic}... | Rust | 0 |
fn create_category_links(&mut self) -> String {
let mut output: String = String::from("<li><a href='/index.html'>Home</a></li>\n");
let mut categories: Vec<String> = self.categories.iter().map(String::from).collect();
categories.sort();
for cat in categories {
output.push_s... | Rust | 0 |
print(f" • keyword_manager.{func}")
def main():
"""Run all demos"""
print("🚀 ADVANCED KEYWORD MANAGEMENT DEMO")
print("=" * 50)
# Run all demos
demo_basic_management()
demo_search_discovery()
demo_analytics()
demo_import_export()
demo_automation()
demo_testing_validation... | Python | 1 |
ub4,
piece: ub1,
indp: *const ::std::os::raw::c_void,
rcodep: *mut ub2,
) -> sword;
}
extern "C" {
pub fn OCIStmtExecute(
svchp: *mut OCISvcCtx,
stmtp: *mut OCIStmt,
errhp: *mut OCIError,
iters: ub4,
rowoff: ub4,
snap_in: *const OCISnapshot... | Rust | 0 |
0.5, (255, 255, 255), 2)
# pixel_width = 2*radius
# # # obtain depth for each ArUco marker
# distance = (focal_length*tomato_dimension)/pixel_width
# # #transforming pixel coordinates to world coordinates
# world_x = (cX - center_x)/focal_length*distance
... | Python | 1 |
- r)
top_hits = pos[:, 1] > (H - r)
if np.any(top_hits):
vy = vel[top_hits, 1]
incoming = vy > 0
impulse_y_total += np.sum(2.0 * m * np.abs(vy[incoming]))
vel[top_hits, 1] *= -1
pos[top_hits, 1] = (H - r) - (pos[top_hits, 1] - (H - r))
# Particle-particle collisions ... | Python | 1 |
vec.len() {
let name = &name_vec[i];
let ord: usize = ord_vec[i].into();
let fun: u64 = fun_vec[ord].into();
let fun_off = fun - text_vaddr as u64 + text_off as u64;
if syscall_regex.is_match(name) {
let syscall_num: u16;
reader.seek(SeekFrom::Start(fun_of... | Rust | 0 |
client.join().expect("couldn't join client thread");
});
}
#[test]
fn rt_sigaction() {
run_test(2, [0xff; 16], move |i, platform, handler| {
let act = [0, 1, 2, 3];
let act_2 = [3, 2, 1, 0];
if i % 2 == 0 {
let mut oldact = None;
assert_eq!(
... | Rust | 0 |
["bar", "baz", "baz", "foo", "qux"],
["yes", "yes", "two", "two", "yes"],
]
index_expected = MultiIndex.from_arrays(
arrays_expected, names=["first", "second"]
)
series_expected = Series(np.ones(5), index=index_expected)
tm.assert_series_equal... | Python | 1 |
evice = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
VGG16 = VGG16().to(device)
optimizer = optim.SGD(VGG16.parameters(), lr=0.01)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=50, gamma=0.5)
# define parameters and running for 200 epochs
total_epoch = 200
train_batch = len(cifar100_trai... | Python | 1 |
for Nonce {} failed with {:?}, current valset {} / {}",
latest_cosmos_valset.nonce, cost, current_valset.nonce, current_valset_from_eth
);
let hash = encode_valset_confirm_hashed(gravity_id.clone(), latest_cosmos_valset.clone());
// there are two possible encoding problems that could... | Rust | 0 |
doc = "`write(|w| ..)` method takes [lcdm22w::W](lcdm22w::W) writer structure"]
impl crate::Writable for LCDM22W {}
#[doc = "LCD Memory 22/23"]
pub mod lcdm22w;
#[doc = "LCD Memory 24/25\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::w... | Rust | 0 |
:Add, std::ops::Add<$ty>, add, $name, $ty);
finite!(@op => std::ops::Sub, std::ops::Sub<$ty>, sub, $name, $ty);
finite!(@op => std::ops::Div, std::ops::Div<$ty>, div, $name, $ty);
finite!(@op => std::ops::Mul, std::ops::Mul<$ty>, mul, $name, $ty);
impl std::convert::TryFrom<$ty> for $na... | Rust | 0 |
etectron2DetectionModel
from sahi.predict import get_sliced_prediction
from sahi.utils.detectron2 import Detectron2TestConstants
# init model
detector2_detection_model = Detectron2DetectionModel(
model_path=Detectron2TestConstants.FASTERCNN_MODEL_ZOO_NAME... | Python | 1 |
many_single_char_names)]
let (h, s, v) = (self.0, self.1, self.2);
let c = v * s;
let hp = h / 60.0;
let x = c * (1.0 - (hp % 2.0 - 1.0).abs());
let m = v - c;
let (r, g, b) = [(c, x, 0.0), (x, c, 0.0), (0.0, c, x), (0.0, x, c), (x, 0.0, c), (c, 0.0, x)][hp as usize];
... | Rust | 0 |
456);
set_sync(512);
write_all_regs(Regs::new());
};
}
assert_eq!(
ftdi.write_data,
[
MpsseCmd::SetDataBitsLowbyte as u8,
0x0 as u8,
0xb as u8,
ClockBitsOut::MsbNeg as u8,
0x7 as u8,
Command:... | Rust | 0 |
out of scope), the lock will be unlocked.
/// This structure is created by the lock_awake method on ClockControlConfig
pub struct LockAwake {}
/// A RAII implementation of a "scoped lock" for PLL/2 frequency.
/// When this structure is dropped (falls out of scope), the lock will be unlocked.
/// This structure is cre... | Rust | 0 |
from micropython import const
from trezor.enums import MessageType
if False:
from typing import Union
from trezor import protobuf
from trezor.messages import (
StellarAccountMergeOp,
StellarAllowTrustOp,
StellarBumpSequenceOp,
StellarChangeTrustOp,
StellarCreateAcc... | Python | 1 |
in bytes. Base CipherEngine assumes 32.
fn key_length(&self) -> usize { 32 }
/// Length of the initialization vector in bytes. Base CipherEngine assumes 16.
fn iv_length(&self) -> usize { 16 }
fn encrypt_stream(&self, key: &[u8], iv: &[u8]) -> Box<Transform>;
fn decrypt_stream(&self, key: &[u8],... | Rust | 0 |
matches.set((w_mate, w), 0);
free_men.push_back(w_mate);
break;
}
}
}
if !b_paired {
free_men.push_back(b);
}
}
// reduce matrix to pairs
for i in 0..matches.rows() {
for j ... | Rust | 0 |
::FetchWeak as i64, out.index() as i64, 0i64, 0i64, )
}
/// Gets all registers of this task.
pub unsafe fn get_all_registers(
&self,
ptr: u64,
len: u64,
) -> i64 {
self.cap.call(BasicTaskRequest::GetAllRegisters as i64, ptr as i64, len as i64, 0i64, )
}
/// Gets all softuser registers of this task.
pub... | Rust | 0 |
self.v_reg[x] = new_vx;
self.v_reg[0xF] = new_vf;
},
// 8XY5 - VX -= VY
// Same as the last one except subtraction instead of addtion.
(8,_,_,5) => {
let x = digit2 as usize;
let y = digit3 as usize;
... | Rust | 0 |
from django.db.models import Count, Manager
class ExampleManager(Manager):
def bulk_create(self, objs, batch_size=None, ignore_conflicts=False):
super().bulk_create(objs, batch_size=batch_size, ignore_conflicts=ignore_conflicts)
uuids = [data.uuid for data in objs]
examples = self.in_bulk(... | Python | 1 |
ed features: `\"Win32_Networking_Clustering\"`*"]
pub type CLUSTER_CSV_VOLUME_FAULT_STATE = i32;
#[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"]
pub const VolumeStateNoFaults: CLUSTER_CSV_VOLUME_FAULT_STATE = 0i32;
#[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"]
pub const VolumeState... | Rust | 0 |
in([sent.text for sent in doc.sents][:self.top_n])
centrality = nx.pagerank(graph)
sorted_terms = sorted(centrality.items(), key=lambda x: x[1], reverse=True)
keywords = {term for term, _ in sorted_terms[:self.top_n * 2]}
summary_sents = []
for sent in doc.sents:
if ... | Python | 1 |
"""SNMP constants."""
CONF_ACCEPT_ERRORS = "accept_errors"
CONF_AUTH_KEY = "auth_key"
CONF_AUTH_PROTOCOL = "auth_protocol"
CONF_BASEOID = "baseoid"
CONF_COMMUNITY = "community"
CONF_DEFAULT_VALUE = "default_value"
CONF_PRIV_KEY = "priv_key"
CONF_PRIV_PROTOCOL = "priv_protocol"
CONF_VERSION = "version"
CONF_VARTYPE = "v... | Python | 1 |
# Copyright 2018 Tecnativa - David Vidal
# Copyright 2020 Tecnativa - João Marques
# Copyright 2022 NuoBiT - Eric Antones
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo import fields, models
class SaleReport(models.Model):
_inherit = "sale.report"
product_brand_id = fields.Man... | Python | 1 |
n scheduling an experiment.
CANNOT_CREATE_EXPERIMENT_CAMPAIGN_WITH_CUSTOM_BUDGET (24):
Cannot use custom budget on base campaign
when scheduling an experiment.
STATUS_TRANSITION_INVALID (25):
Invalid status transition.
DUPLICATE_EXPERIM... | Python | 1 |
// let mut prev_fund_month = HashMap::<u32, Month>::new();
let fund_budget: HashMap<_, _> = fund.iter().zip(budget.iter()).collect();
let mut prev_fund_month: HashMap<u32, Month> = fund
.iter()
.map(|x| (*x, start.month().previous()))
.collect();
// Keep the same with real world, w... | Rust | 0 |
builder.append_extension(key_usage).unwrap();
let ext_key_usage = ExtendedKeyUsage::new()
.client_auth()
.server_auth()
.other("2.999.1")
.build()
.unwrap();
builder.append_extension(ext_key_usage).unwrap();
let subject_key_identifier = SubjectKeyIdentifier::new(... | Rust | 0 |
t_with(active)
<= <Runtime as frame_system::Config>::BlockWeights::get().max_block
|| active == all_voters
{
active += 1;
}
println!("can support {} voters to yield a weight of {}", active, weight_with(active));
}
}
pub use heck;
pub use proc_macro2;
pub use quote;
pub use syn;
use std::fmt;
pub mod ... | Rust | 0 |
_profit_reward(test_samples, test_tokens, X)
# Check shape
assert result.shape == (5, 3, 1)
# Manually verify some calculations
# For price 9.99, cost 5.0, tax 10%:
# revenue_after_tax = 9.99 * (1 - 0.1) = 8.991
# gross_profit = 8.991 - 5.0 = 3.991
expected_prof... | Python | 1 |
import numpy as np
import random
import numpy as np
def read_fvecs(filename):
with open(filename, 'rb') as f:
dim = np.fromfile(f, dtype=np.int32, count=1)[0]
f.seek(0)
data = np.fromfile(f, dtype=np.float32)
data = data.reshape(-1, dim + 1)[:, 1:]
return data
def read_ivecs(f... | Python | 1 |
bda x, y: df._F.format_string(f"%s{separator}%s", x, y),
cols_casted,
),
).otherwise(df._F.lit(None))
else:
init_value, *values = [
df._F.when(~nm, col).otherwise(df._F.lit(""))
for col, nm in... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
# Please refer to https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html#a-pure-python-style-configuration-file-beta for more details. # noqa
# mmcv >= 2.0.1
# mmengine >= 0.8.0
from mmengine.config import read_base
with read_base():
from ..common... | Python | 1 |
nd(wet)
water_mates.append(waters_generated)
numbering_stuff.append([int(position), len(waters_generated)-1])
# nitrile mode
if len(master) == 2:
wet = hydro(master[0], atom, master[1])
waters_generated.append(wet)
water_mates.append(waters_ge... | Python | 1 |
from typing import List
from pyrep.objects.joint import Joint
from rlbench.backend.task import Task
from rlbench.backend.conditions import JointCondition
class PressSwitch(Task):
def init_task(self) -> None:
switch_joint = Joint('joint')
self.register_success_conditions([JointCondition(switch_joi... | Python | 1 |
__author__ = 'chen zhourong'
#from gensim.models import Word2Vec
def compactness_score(model_path, topic_file_path, with_gensim = True):
"""
model_path: Word2Vec model file
topic_file_path:Each line in the file is a topic, represented as
a list of words separated by spaces
Output: Print compactness score ... | Python | 1 |
Bound::PosInf),
Itv::from_double_closed(0., 4.),
]);
assert_eq!(itv1().assign(&trans), c);
let mut n_trans = HashMap::new();
n_trans.insert(0, AffineTransform::from_coeffs(vec![0., -1., -1.], -1.));
let d = Interval::from_vec(vec![
Itv::from_bounds_closed(... | Rust | 0 |
= *mut ::core::ffi::c_void;
pub type IWICPlanarBitmapSourceTransform = *mut ::core::ffi::c_void;
pub type IWICPlanarFormatConverter = *mut ::core::ffi::c_void;
pub type IWICProgressCallback = *mut ::core::ffi::c_void;
pub type IWICProgressiveLevelControl = *mut ::core::ffi::c_void;
pub type IWICStream = *mut ::core::f... | Rust | 0 |
}
<gh_stars>0
mod channel;
mod common;
mod peer;
mod server;
pub use channel::*;
pub use common::*;
pub use peer::*;
pub use server::*;
<gh_stars>0
/*!
* Random data generation utilities for use in testing the BIRCH algorithm.
*/
pub mod distribution;
use super::utils::check;
use hex_literal::hex;
#[test]
fn aes1... | Rust | 0 |
elf.store)
def keys(self):
return self.store.keys()
def append(self, key, values):
"""Append a new record to the persistent file"""
##print("append:%s %s" % (key, values))
if self.filename != None:
with open(self.filename, 'a') as f:
f.write("\nADD ... | Python | 1 |
# Copyright (c) 2021 - present / Neuralmagic, Inc. 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 required b... | Python | 1 |
# %%
# import
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# %%
# load data
mtcars = pd.read_csv('.data/mt_cars.csv')... | Python | 1 |
.nakadi_host("http://localhost:8080")
.subscription_discovery(SubscriptionDiscovery::OwningApplication(
"test-suite".into(),
vec![EVENT_TYPE_NAME.into()],
))
.max_uncommitted_events(60000)
.set_min_idle_worker_lifetime(Duration::from_secs(15))
.commit_s... | Rust | 0 |
eason)
await interaction.response.send_message(embed=confirm_embed, view=view, ephemeral=True)
@app_commands.command(name="lookup", description="Looks up a user ID or username in the federated ban list.")
@discord.app_commands.describe(query="The User ID or username to search for.")
@has_mo... | Python | 1 |
from Crypto.Util.number import *
from secret import flag
m = bytes_to_long(flag)
n = getPrime(1024)
e = 65537
c = pow(m, e, n)
with open("Session2\primeMod\out.txt", "w") as f:
f.write(f"n = {n}\n")
f.write(f"e = {e}\n")
f.write(f"c = {c}\n") | Python | 1 |
::csv_encode_uuids",
deserialize_with = "crate::domain::from_csv"
)]
pub bundles: Vec<Uuid>,
/// Whether the response should be returned as
/// [`Bundles`](ListEntryResponse::Bundles) or [`List`](ListEntryResponse::List)
#[serde(skip_serializing_if = "ListEntryGroupBy::is_none")]
#[serd... | Rust | 0 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
import torch
from fairseq.data import LanguagePairDataset, TokenBlockDataset
from fairseq.data.concat_dataset import ConcatDa... | Python | 1 |
nomask(text: *const u8, offset: usize, text_len: usize,
needle: __m128i, needle_len: usize) -> u32 {
//debug_assert!(text_len + offset <= text.len()); // saturates at 16
//debug_assert!(needle_len <= 16); // saturates at 16
let text = _mm_loadu_si128(text.offset(offset as _) as *const... | Rust | 0 |
from_slice(header_data)
.map_err(|e| if e.is_data() { MalformedHeader } else { MalformedJson })?;
let version = json_header.version.parse().map_err(|_| MalformedVersion)?;
let header = Header {
version: version,
game_uuid: json_header.game_uuid.parse().map_err(|_| MalformedGameUuid)?,
... | Rust | 0 |
import pandas as pd
import random
import os
DATA_PATH = '/content/netflix_titles.csv'
def load_data():
if not os.path.exists(DATA_PATH):
print("❗ Please run the ETL pipeline first (pipeline_ml.py).")
return None
return pd.read_csv(DATA_PATH)
def recommend_shows(df, mood):
mood = mood.lowe... | Python | 1 |
cher.get_account(0).unwrap();
let contract_addr = dispatcher.deploy(deployer_addr.clone(), gas).unwrap();
dispatcher.set_contract_addr(&contract_addr, ANONYMOUS_ASSET_ABI_PATH).unwrap();
println!("Deployer address: {:?}", deployer_addr);
println!("deployed contract address: {}", contract_addr);
// ... | Rust | 0 |
from funasr import AutoModel
from funasr.utils.postprocess_utils import rich_transcription_postprocess
model_dir = "./"
model = AutoModel(
model=model_dir,
vad_model="fsmn-vad",
vad_kwargs={"max_single_segment_time": 30000},
# device="cuda:0",
hub="hf",
)
# en
res = model.generate(
input=f"{... | Python | 1 |
N = int(input())
field = []
for _ in range(N):
field.append(list(input().rstrip()))
res = 0
def find_max_cnt(line):
previous = line[0]
cnt = 1
curr = 1
for candy in line[1:]:
if candy == previous:
curr += 1
cnt = max(cnt, curr)
else:
previous = ca... | Python | 1 |
KEN_VAR).ok())
}
}
impl Folder {
pub fn as_path(&self) -> Result<String> {
let path = shellexpand::full(&self.path)?;
Ok(path.to_string())
}
pub fn github_name(&self) -> &str {
&self.github
}
}
const APP_NAME: &str = "repo-server";
const CONFIG_FILE: &str = "config.toml";
impl Config {
pu... | Rust | 0 |
from django.db import connection, models
from django.db.models.expressions import RawSQL
def test_plain():
cursor = connection.cursor()
cursor.execute("some sql") # $getSql="some sql"
def test_context():
with connection.cursor() as cursor:
cursor.execute("some sql") # $getSql="some sql"
... | Python | 1 |
'm mad?\" said Alice.")
}
#[no_mangle]
pub fn cb_write_test_test4(_v : &'static [u8]) -> Result<(), Error> {
Err(Error::NonWriteable)
}
#[no_mangle]
pub fn cb_read_test_test4() -> Result<&'static [u8], Error> {
Ok(b"\"You must be,\" said the Cat,")
}
#[no_mangle]
pub fn cb_write_test_test5(_v : &'static [u8]... | Rust | 0 |
else:
raise ValueError("combiner_path should be in ['sum', 'combiner']")
if args.dataset.lower() == 'cirr':
group_recall_at1, group_recall_at2, group_recall_at3, recall_at1, recall_at5, recall_at10, recall_at50 = \
cirr_val_retrieval(combining_function, clip_model, preprocess)
... | Python | 1 |
from __future__ import annotations
import typing as T
import discord
from core.embeds import EmbedBuilder
from utils import emote
__all__ = ("EmbedSend", "EmbedCancel")
class EmbedSend(discord.ui.Button):
view: EmbedBuilder
def __init__(self, channel: discord.TextChannel):
self.channel = channel
... | Python | 1 |
u16, dev_port_2 as u16);
}
pub fn configure_port_to_port_forwarding(dev_port_1: u32, dev_port_2: u32) {
L2Layer::configure_from_port_to_port(MANAGER.lock().unwrap().session_handler, dev_port_1 as u16, dev_port_2 as u16);
L2Layer::configure_from_port_to_port(MANAGER.lock().unwrap().session_hand... | Rust | 0 |
els=64, out_channels=32, kernel_size=(1, 3), stride=(1, 1), padding=(0, 0)),
nn.BatchNorm2d(32),
nn.PReLU(),
)
self.convT4 = nn.Sequential(
nn.ConvTranspose2d(in_channels=64, out_channels=32, kernel_size=(1, 3), stride=(1, 2), padding=(0, 0)),
nn.BatchNor... | Python | 1 |
import colorlog
import logging
def handler_log():
"""
Cria e retorna um handler de logging para saída em console com formatação colorida.
O handler utiliza colorlog.ColoredFormatter para aplicar cores aos níveis de log
e formata as mensagens no padrão:
"%(log_color)s %(asctime)s | %(levelname)... | Python | 1 |
.position(x, y);
let y = y + font_size + 2.0;
draw.rect((x, y), tex.size()).stroke(2.0).alpha(0.5);
draw.image(tex).position(x, y);
}
<filename>src/test/run-pass/capture_nil.rs
// compile-flags:-Z no-opt
use comm::*;
// This test has to be setup just so to trigger
// the condition which was causing us a ... | Rust | 0 |
let poll = Self::poll()?;
let served_client_connection_arena_capacity = self.start_server_listeners()?;
let served_client_connection_arena = Arena::with_capacity(served_client_connection_arena_capacity);
let XXXXX = self.start_worker_threads(&terminate, &self.logical_core_utilization_detail.worker_loops)?;
... | Rust | 0 |
import pytest # noqa: F401
def test_assistant_group_create(ensure_logged_in):
page = ensure_logged_in
# Create 3 assistants
for i in range(1, 4):
page.goto("http://localhost:8000/assistants/")
page.wait_for_selector("#assistant-form")
page.fill("input#id_name", f"GroupAssistant{i... | Python | 1 |
import torch
class TensorboardWriter:
@staticmethod
def write_tensorboard(writer, panel, data_dict, step):
complex_dict = False
if "scalars" in data_dict:
scalar_data_dict = data_dict["scalars"]
TensorboardWriter.write_scalar_tensorboard(writer, panel, scalar_data_dict,... | Python | 1 |
import torch
import pytest
import numpy as np
from numpy.testing import assert_allclose
@pytest.fixture
def random_state():
return np.random.RandomState(None) # (1249563438)
def test_window_view(random_state):
from cplxmodule.utils import window_view
np_x = random_state.randn(2, 3, 1024, 2, 2)
tr... | Python | 1 |
import os
import sys
from cryptol.connection import connect
cry = connect(url="http://localhost:8080/", reset_server=True)
project_file = os.path.abspath(sys.argv[1]
if len(sys.argv) > 1
else "run-docstrings-data/project.toml")
print("Using " + os.path.... | Python | 1 |
for taxa_idx in 0..draws.len() {
let old_val = bootstrap_counts.get_unchecked(taxa_idx, sample_idx);
let new_val = old_val + draws[taxa_idx];
bootstrap_counts.set_unchecked(taxa_idx, sample_idx, new_val);
}
}
}
log::debug!("`make_w... | Rust | 0 |
) -> Self:
# pandas is a required dependency of dask so it's safe to import this
from narwhals._pandas_like.group_by import PandasLikeGroupBy
if not partition_by:
assert order_by is not None # help type checkers # noqa: S101
# This is something like `nw.col('a').cum... | Python | 1 |
NS_OF_PREFIX_W_TRIPLE_FREE:
alt_statements = generate_alt_statements_prefix_with_triple_wo_object(
bot,
target,
sentence,
prefix,
args.alts,
args.override_temperature,
generate_statement_missing_o... | Python | 1 |
# coding: utf-8
from api.database.dto_generator.dtogeneratorservice import DTOGeneratorService
from api.database.dto_generator.pythondtogenerator import PythonDTOGenerator
from api.database.dto_generator.typescriptdtogenerator import TypeScriptDTOGenerator
from api.database.model.customtrack import CustomTrackSchema
f... | Python | 1 |
"""
Copyright (c) 2023 Combo Gang. All rights reserved.
This work is licensed under the terms of the MIT license.
For a copy, see <https://opensource.org/licenses/MIT>.
"""
import json
from src.base import database
from pymongo import MongoClient
from pymongo.server_api import ServerApi
from enum import Enum
def g... | Python | 1 |
from evennia import create_script
from evennia.contrib.grid import wilderness
from evennia.utils import logger
from world.overworld.provider import OverworldMapProvider
class Overworld(wilderness.WildernessScript):
_INSTANCE = None
_NAME = "overworld"
@classmethod
def get_instance(cls):
if c... | Python | 1 |
t_pk_receiver]
.push_opcode(OP_SHA256)
.push_opcode(OP_TOALTSTACK);
stk_size -= 2;
// Process the fee output
let mut pre_value_blob = vec![];
pre_value_blob.extend(&serialize(&asset)); // asset
pre_value_blob.push(1u8); // explicit prefix;
let mut ... | Rust | 0 |
from mido import MidiFile
def midi_note_to_freq(note):
return round(440.0 * 2 ** ((note - 69) / 12), 2)
def midi_velocity_to_gain(velocity):
return round(velocity / 127, 2) # normalize 0-127 to 0-1
def calculate_ms_per_slot(mid, minimal_fraction=0.5):
"""
Calculates ticker interval based on tempo and minimal fr... | Python | 1 |
from setuptools import setup
packages = ["windows_toasts", "scripts"]
requires = [
"winrt-runtime~=3.0",
"winrt-Windows.Data.Xml.Dom~=3.0",
"winrt-Windows.Foundation~=3.0",
"winrt-Windows.Foundation.Collections~=3.0",
"winrt-Windows.UI.Notifications~=3.0",
]
with open("README.md", "r", encoding="... | Python | 1 |
[derive(Debug, Copy, Clone)]
pub struct _LEAP_CALIBRATION {
_unused: [u8; 0],
}
#[doc = " \\ingroup Structs"]
#[doc = " Represents a calibration object."]
#[doc = " Not currently of any particular use."]
#[doc = " @since 3.0.0"]
pub type LEAP_CALIBRATION = *mut _LEAP_CALIBRATION;
#[doc = " \\ingroup Stru... | Rust | 0 |
= self.conn.query(query, &[])?;
if data.len() >= 1 {
row_matcher(data.get(0), self.save_folder.clone())
} else {
Err(Error::EmptyQuery)
}
}
pub fn insert_new_rating(
&self,
discord_id: i64,
file_id: i32,
rating: i16,
) -> Res... | Rust | 0 |
F32Store,
F64Store,
I32Store8,
I32Store16,
I64Store8,
I64Store16,
I64Store32,
MemorySize,
MemoryGrow,
I32Const,
I64Const,
F32Const,
F64Const,
RefNull,
RefIsNull,
RefFunc,
I32Eqz,
I32Eq,
I32Ne,
I32LtS,
I32LtU,
I32GtS,
I32GtU,
... | Rust | 0 |
Directives? EnumValuesDefinition?
pub(crate) fn enum_type_definition(p: &mut Parser) {
let _g = p.start_node(SyntaxKind::ENUM_TYPE_DEFINITION);
if let Some(TokenKind::StringValue) = p.peek() {
description::description(p);
}
if let Some("enum") = p.peek_data().as_deref() {
p.bump(Synta... | Rust | 0 |
from django.urls import path
from currency.views import index_view
urlpatterns = [
path("home", index_view, name='index'),
] | Python | 1 |
description: "desc".to_string(),
homepage: None,
version: "v0.4.0".to_string(),
license: "MIT".to_string(),
linux: Some(linux),
macos: None,
};
// Act
let result = serialize_brew(&brew);
// Assert
assert_eq... | Rust | 0 |
from django.contrib import admin
from .models import Booking, Menu
admin.site.register([Booking, Menu])
| Python | 1 |
ed_weights(images, max_weights_matrix, offset)
weights = [[cv2.GaussianBlur(max_weights[i], (0, 0), 2 * sigma) for i in range(len(images))]]
sigma_images = [cv2.GaussianBlur(image.image, (0, 0), sigma) for image in images]
bands = [
[
np.where(
images[i].image.astype(np.... | Python | 1 |
_changed() {
tx.send(Broadcast::Everyone(Game::Players(players.clone())))?;
}
if let Some(state) = game_state.reset_if_changed() {
tx.send(Broadcast::Everyone(Game::Game(state.clone())))?;
}
}
}
trait CanvasExt {
fn send(self, user_id: UserId, event: Canvas) -> R... | Rust | 0 |
_unstable();
pretty_assertions::assert_eq!(remappings, expected);
}
#[test]
fn hardhat_remappings() {
let tmp_dir = tempdir("node_modules").unwrap();
let tmp_dir_node_modules = tmp_dir.path().join("node_modules");
let paths = [
"node_modules/@aave/aave-token/cont... | Rust | 0 |
centroid_dict[0])*0.5
head = centroid_dict[1] + next_vec
bone_coords = [(centroid_dict[link_order[0]],
tail, link_order[0])]
head_r = bone_coords[-1][1]
bone_coords.append(
(head_r, centroid_dict[link_order[-1]], link_order[-1]))
e... | Python | 1 |
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ContextTypes
from modules.config import MAIN_MENU, STATS_MENU
from modules.api.system import SystemAPI
from modules.api.nodes import NodeAPI
from modules.utils.formatters import format_system_stats, format_b... | Python | 1 |
(922_3372_0368_5477_5808, 63), // 2
(1215_7665_4590_5692_8801, 40), // 3
(461_1686_0184_2738_7904, 31), // 4
(745_0580_5969_2382_8125, 27), // 5
(473_8381_3383_2161_6896, 24), // 6
(390_9821_0485_8298_8049, 22), // 7
(922_3372_036... | Rust | 0 |
_box() );
sm.register_handler::<B>( slow2.clone_box() );
sm.register_handler::<C>( slow3.clone_box() );
// create peer with stream/sink
//
let (mut peer, peer_mb, _peer_addr) = CborWF::create_peer
(
"server", server, 1024, 1024,
AsyncStd,
Some(Arc::new( Semaphore::new(2) )),
None
).expect( "... | Rust | 0 |
V: Into<DatabaseValue<'a>>,
{
self.columns.push(column.into());
self.values.push(value.into());
self
}
/// Adds `WHERE` conditions to the query. See
/// [Comparable](trait.Comparable.html#required-methods) for more examples.
///
/// ```rust
/// # use prisma... | Rust | 0 |
import json
import yaml
import pickle
import numpy as np
from pypcd import pypcd
import mmcv
def load_json(path):
with open(path, mode="r") as f:
data = json.load(f)
return data
def load_yaml(path):
with open(path, "r") as f:
data = yaml.load(f)
return data
def load_pkl(path):
... | Python | 1 |
import os
import shutil
import pytest
import gym
from stable_baselines import A2C
from stable_baselines.bench.monitor import Monitor
from stable_baselines.common.evaluation import evaluate_policy
from stable_baselines.common.cmd_util import make_vec_env
from stable_baselines.common.vec_env import DummyVecEnv, Subproc... | Python | 1 |
preds_dicts['all_bbox_preds'] = preds_dicts['all_bbox_preds'][-1]
preds_dicts['all_pts_preds'] = preds_dicts['all_pts_preds'][-1]
preds_dicts = self.bbox_coder.decode(preds_dicts)
num_samples = len(preds_dicts)
ret_list = []
for i in range(num_samples):
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.