text string | label_name string | labels int64 |
|---|---|---|
Rc};
#[derive(Parser)]
pub struct AddCommand {
addon_url: Option<String>,
#[clap(
short,
long,
help = "Indicate, if the addon is only a dependency for another addon"
)]
#[clap(short)]
dependency: bool,
}
impl AddCommand {
pub fn run(
&mut self,
cfg: &mut... | Rust | 0 |
use env_param::EnvParam;
use std::collections::{HashMap, VecDeque};
use std::convert::*;
use std::hash::Hash;
use std::marker::PhantomData;
use std::ops::Index;
use std::ops::IndexMut;
use std::str::FromStr;
type ModelEvent = aries_model::int_model::event::Event;
pub type Timepoint = VarRef;
pub type W = IntCst;
pu... | Rust | 0 |
e\x18\xf0\
F\x9d\xa7j\xb1\xeb\xb6\x9a\xae\x81.\xa5\xa6j\xbe2\
\xf1\x16\xa1k\x1e\x87'\x8a\xbcC\xe2mXx\x96\xfe\
\xce\xd2\xe8\x0d?DK\xd8l\xedtX\xa2\x97\xedw\
\xbc\xde\x93\xad\xdc\xe8\x9a\x5c\xfe=\xf1\x05\xd2\xeb^\x11\
\xbf\xbc\xd7>\x1f^\xde\xb3Y\xf8\x87O\xd65-i\
\xed5\x98\xfc?x\xae\x97\xda\x8e\x87\xa9i\xd6\xb1\xd8\
\x0bk\... | Python | 1 |
t overrides
/// the session's keyspace for the batch.
///
/// <b>Note:</b> If not set explicitly then the batch will inherit the keyspace
/// of the first child statement with a non-empty keyspace.
///
/// @public @memberof CassBatch
///
/// @param[in] batch
/// @param[in] keyspace
... | Rust | 0 |
true => QueryResponse {
var_values: cs.subst.make_identity(self.tcx),
region_constraints: QueryRegionConstraints::default(),
certainty: Certainty::Ambiguous,
value: (),
},
false => QueryResponse {
var_values:... | Rust | 0 |
world.insert(CurrentStageData::default());
}
fn create_start_window(world: &mut World) {
let window_size = DEFAULT_GRID_SIZE * CELL_SIZE;
let font_handle: Handle<FontAsset> = world.read_resource::<Loader>().load(
"fonts/square.ttf",
TtfFormat,
(),
&world.read_reso... | Rust | 0 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: contact.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
... | Python | 1 |
import k3d
def generate():
plt_text_0_0 = k3d.text2d('(0,0)',
position=(0, 0),
reference_point='lt')
plt_text_0_05 = k3d.text2d('(0,0.5)',
position=(0, 0.5),
reference_point='lc')
plt_... | Python | 1 |
};
use wasmer_runtime::{imports, instantiate, Ctx, Func};
#[test]
fn read_strings() -> Result<(), Box<dyn Error>> {
let wasm = include_bytes!("../get-string.wasm");
let import_object = imports! {
"env" => {
"abort" => func!(abort),
},
};
let instance = instantiate(&wasm[..]... | Rust | 0 |
Ok(())
} else {
Err(std::io::Error::new(std::io::ErrorKind::Other, "No dest node for lookup_value"))
}
}
fn try_find_node_req(&mut self) -> Result<()> {
for _ in 0..self.proto_params.alpha {
if let Some(node_entry) = NodeMain::get_next_init_node(&self.find_node... | Rust | 0 |
# Generated by Django 2.0.5 on 2018-05-16 16:48
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='List',
fields=[
('id', models.AutoField(aut... | Python | 1 |
asher(blake2_128_concat) T::AccountId, hasher(blake2_128_concat) T::KittyIndex => Option<T::KittyIndex>;
//kitty成员信息(parent,wife,brothers,children)
// pub KittyFamilyInfo get(fn kitty_faily_info): map hasher(blake2_128_concat) T::KittyIndex => Option<KittyFamily<T>>;
// 猫的父母
pub KittyParents get(fn kitt... | Rust | 0 |
// Just print the fd numbers; don't try to print the path or any
// information about it, because this information is otherwise
// unavailable to safe Rust code.
f.debug_struct("AsyncStreamDuplexer")
.field("raw_read_grip", &self.as_raw_read_grip())
.field("raw_wr... | Rust | 0 |
::U64(9999)));
}
}
<gh_stars>0
use super::utils;
#[cfg(feature = "dim2")]
use super::Polyline;
#[cfg(feature = "dim3")]
use super::{IndexBuffer, TriMesh};
use alga::general::Real;
use na;
#[cfg(feature = "dim3")]
use na::{Point2, Point3, Vector3};
/// Generates a UV sphere.
#[cfg(feature = "dim3")]
pub fn sphere<N... | Rust | 0 |
'''Реализуйте класс UpperPrint. При создании экземпляра класс не должен принимать никаких аргументов.
Экземпляр класса UpperPrint должен являться контекстным менеджером, который внутри блока with позволяет выполнять все операции записи в стандартный поток вывода sys.stdout в верхнем регистре.
Примечание 1. Наглядные ... | Python | 1 |
nfigured model: {model_name}")
except Exception as e:
model_name = "us.anthropic.claude-sonnet-4-20250514-v1:0"
print(f"Could not load config ({e}), using default model: {model_name}")
discovery_agent = VulnerabilityDiscoveryAgent(model_name=model_name)
analysis_request = """
Please di... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from contourpy import FillType, LineType, ZInterp
from contourpy.enum_util import as_fill_type, as_line_type, as_z_interp
from . import util_test
if TYPE_CHECKING:
from collections.abc import Callable
@pytest.mark.parametrize("... | Python | 1 |
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
from importlib import import_module
train_params = {'lr': 1e-4, # **
'num_hidden': [128]*10, # **
'FNN_hidden': [], # **
'FNN_type': 'linear', # 'non-linear'
'process_no... | Python | 1 |
#[test]
fn test_eth_get_block_transaction_count_by_hash() {
let mut client = ConnectionWrapper::new_from_env(None);
unlock_account(&mut client, Address::try_from(ADDRESS2).unwrap());
prefund_account(&mut client, Address::try_from(ADDRESS2).unwrap());
simulate_transaction(
&mut client,
Ad... | Rust | 0 |
sponse.iter_content(*args, **kwargs)
@staticmethod
def headers(self, *args, **kwargs):
'''
headers
'''
return self._response.headers(*args, **kwargs)
@property
def cookies(self):
'''
返回当前页面设置的cookies
'''
return self._response.cookies
... | Python | 1 |
48i32;
#[doc = "*Required features: `\"Win32_Globalization\"`*"]
pub const U_JG_YUDH_HE: UJoiningGroup = 49i32;
#[doc = "*Required features: `\"Win32_Globalization\"`*"]
pub const U_JG_ZAIN: UJoiningGroup = 50i32;
#[doc = "*Required features: `\"Win32_Globalization\"`*"]
pub const U_JG_FE: UJoiningGroup = 51i32;
#[doc... | Rust | 0 |
by a signed phase, then create the snapshots.
debug_assert!(Self::snapshot().is_none());
Self::create_snapshot()?
} else {
0
};
<CurrentPhase<T>>::put(Phase::Unsigned((enabled, now)));
Self::deposit_event(Event::UnsignedPhaseStarted(Self::round()));
Ok(weight.saturating_add(T::DbWeight::get().write... | Rust | 0 |
();
let parents = self.get_children(&self.overlay.root);
for w in parents {
for c in self.get_children(&w) {
if self.is_visible(&c) {
windows.push(c);
}
}
}
windows
}
/// This function is responsible f... | Rust | 0 |
ITER_DEFAULT = 0,
#[doc = ""]
JSON_WRITER_OMIT_BINARY_VALUES = 1,
#[doc = ""]
JSON_WRITER_OMIT_DOUBLE_TYPE_PRESERVATION = 2,
#[doc = ""]
JSON_WRITER_PRETTY_PRINT = 4,
}
#[repr(i32)]
#[non_exhaustive]
#[doc = ""]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum cef_pdf_print_margin_typ... | Rust | 0 |
b287e0f3f4a",
"params": {
"iv": "9476702ab99beff3e8012eff49ffb60d"
}
},
"kdf": {
"function": "pbkdf2",
"message": "",
"params": {
"c": 16,
"dklen": 32,
"prf": "hmac-sha256",
"salt": "dd35b0c08ebb672fe18832120a55cb8098f428306bf5820f5486b514f61eb712"
}
}
... | Rust | 0 |
from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext, MessageHandler, Filters
# Botunuzun API anahtarını buraya ekleyin
API_KEY = '7634758807:AAEPjGIVNjRt06SOZIl2tkWoRbKkuvVL5SA'
# Bot komutları
def start(update: Update, context: CallbackContext) -> None:
update.message.re... | Python | 1 |
else {
q
}
}
fn delete_query_string(tag: Option<String>) -> String {
let sub_create_query = format!(
"
SELECT Header.hash FROM DhtOp
{}
",
Self::common_query_string()
);
let sub_create_query = Self::add_tag(s... | Rust | 0 |
="0:3")] idx: u8,
}
#[derive(Debug, Default, PackedStruct)]
#[packed_struct(bit_numbering="lsb0", size_bytes="1")]
pub struct ClkMode {
#[packed_field(bits="0")] dot_clk: u8,
#[packed_field(bits="2")] sft_ld: u8,
#[packed_field(bits="3")] dclk_div: u8,
#[packed_field(bits="4")] sft4: u8,... | Rust | 0 |
import tmoutproc as top
import sys
__HYDROGEN_MASS__ = 1.00794080
def modify_mass_to_element(coord, indices, element):
for index in indices:
coord[3, index] = element
return coord
def determine_indices(input_file):
indices = list()
with open(input_file, 'r', encoding='utf-8') as file:
for line in file:
i... | Python | 1 |
ait;
r.switch();
Ok(warp::reply::with_status(
"Ok",
http::StatusCode::OK,
))
}
fn setting_json_body() -> impl Filter<Extract = (Setting,), Error = warp::Rejection> + Clone {
warp::body::content_length_limit(1024 * 16).and(warp::body::json())
}
extern crate foo;
fn main() {}
// Copyrigh... | Rust | 0 |
{
[x, , y] = [3, 4, 5]
}
"#,
r#"
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.f1 = f1;
exports.f2 = f2;
exports.f3 = f3;
exports.f4 = f4;
exports.y = exports.x = void 0;
let x = 0;
exports.x = x;
let y = 0;
exports.y = y;
function f1() {
({
x
} = {
x: 1
}... | Rust | 0 |
print("%.3f\t%.3f\t%.3f\t%.3f" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))
yield hps.data.sampling_rate, (np.concatenate(audio_opt, 0) * 32768).astype(np.int16)
def handle_control(command):
if command == "restart":
os.execl(g_config.python_exec, g_config.python_exec, *sys.argv)
elif command == "exit... | Python | 1 |
e(op); }
script::Instruction::PushBytes(bytes) => {
// Any one-byte pushes, except -0, which can be interpreted as numbers, should be
// reserialized as numbers. (For -1 through 16, this will use special ops; for
// others it'll just reserializ... | Rust | 0 |
sername or email already exists"
)
except Exception as e:
db.rollback()
raise HTTPException(
status_code=500, detail=f"Internal server error: {str(e)}"
)
@staticmethod
def delete_user(db: Session, user_id: str):
"""Elimina un usuar... | Python | 1 |
egui_screen_descriptor,
);
self.egui_state.checkpoint("egui");
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("RenderPass"),
color_attachments: &[wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgp... | Rust | 0 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: sda_virtual_network_info
short_description: Information module for Sda Virtual Network
description:
- Get all Sda ... | Python | 1 |
type constructors
///
/// This will eventually change to `type Connection<'a>` on [`DieselPool`]
pub trait BorrowedConnection<'a> {
/// The smart pointer returned by this connection pool.
type Connection: Deref<Target = PgConnection>;
}
/// A connection pool for Diesel database connections
///
/// If you don'... | Rust | 0 |
тимиллионною
миллиард миллиардного миллиардному миллиардном миллиардный миллиардным миллиардом миллиарда миллиарде миллиарду
миллиардов
лярд лярда лярды лярдом лярдами лярдах лярдов
млрд
триллион триллионного триллионному триллионном триллионный триллионным триллионом триллиона триллионе триллиону
триллионов тр... | Python | 1 |
F = set(namespace['F'])
test_cases = namespace['test_cases']
ra = RA(Q, E, T, R0, U, q0, F)
# result = 'Emptiness' if ra.emptiness() else 'Not Emptiness'
# print(result)
for i, test in enumerate(test_cases):
result = 'Accepted' if ra.accepts(test) else 'Rejected'
print(f"Test cas... | Python | 1 |
SciterGetVariable: extern "system" fn(hwndOrNull: HWINDOW, path: LPCWSTR, value: *mut VALUE) -> UINT,
// since 4.4.5.4
pub SciterElementUnwrap: extern "system" fn(pval: *const VALUE, ppElement: *mut HELEMENT) -> SCDOM_RESULT,
pub SciterElementWrap: extern "system" fn(pval: *mut VALUE, pElement: HELEMENT) -> SCDOM_... | Rust | 0 |
escaped correctly'),
(r'a\\bc', r'%a\\\\bc%', r'\ is not escaped correctly'),
( 'a\nbc', r'%a\\nbc%', r'\n is not escaped correctly'),
(r'a\_bc', r'%a\_bc%', r"\_ shouldn't be escaped"),
(r'a\%bc', r'%a\%bc%', r"\% shouldn't be escaped"),
( 'abc_d... | Python | 1 |
il Admin Panel"
# Path to `sendmail` command
CMD_SENDMAIL = "/usr/sbin/sendmail"
# SMTP server address, port, username, password used to send notification mail.
NOTIFICATION_SMTP_SERVER = "localhost"
NOTIFICATION_SMTP_PORT = 587
NOTIFICATION_SMTP_STARTTLS = True
NOTIFICATION_SMTP_USER = "no-reply@localhost.local"
NOT... | Python | 1 |
false)
}.set_range_function(range_function.into())
.set_displacement(displacement)
.set_frequency(worley_frequency)
} else {
error(&format!("Attempted to configure module with worley settings but the settings aren't worley: {:?}", conf));
module
}
}
pub fn apply_constant... | Rust | 0 |
::builder(method).unwrap();
ctx.set_verify_callback(SslVerifyMode::PEER, |_, _| false);
assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_err());
});
run_test!(verify_trusted_callback_override_ok, |method, stream| {
let mut ctx = SslContext::builder(method).unwrap();
ctx.set_verify_callback(S... | Rust | 0 |
#!/usr/bin/env python
from setuptools import find_packages, setup
extras_require = {
"test": [ # `test` GitHub Action jobs uses this
"pytest>=6.0", # Core testing package
"pytest-xdist", # Multi-process runner
"pytest-cov", # Coverage analyzer plugin
"hypothesis>=6.2.0,<7.0", #... | Python | 1 |
ypes::Timestamp> {
Ok(prost_types::Timestamp {
seconds: datetime.timestamp(),
nanos: i32::try_from(datetime.nanosecond()).map_err(|e| DamlError::new_failed_conversion(e.to_string()))?,
})
}
#[allow(clippy::cast_sign_loss)]
pub fn from_grpc_duration(duration: &prost_types::Duration) -> Duration ... | Rust | 0 |
#[atom]
fn c() -> Atom<i32> {
0
}
// #[reaction]
// fn count_print_when_update() -> Reaction<i32> {
// let c = c();
// let _update = a_reversible().on_update(|| {
// println!("UPDATE !!!");
// c.update(|v| *v = *v + 1)
// });
// c.ge... | Rust | 0 |
WorkspaceNext") {
return Ok(ExternalCommand::FocusWorkspaceNext);
} else if s.starts_with("FocusWorkspacePrevious") {
return Ok(ExternalCommand::FocusWorkspacePrevious);
} else if s.starts_with("NextLayout") {
return Ok(ExternalCommand::NextLayout);
} else if s.starts_with("PreviousL... | Rust | 0 |
ictim: ActorId,
pub attack_velocity: Vector3f,
pub victim_velocity: Vector3f,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct Explosion {
pub flag: bool,
pub actor: ActorId,
pub location: Vector3f,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct ExtendedExplosion ... | Rust | 0 |
,
},
None => continue,
};
let inner = match chunk[1] {
Resp3Frame::Array { ref data, .. } => data,
_ => continue,
};
let parsed = parse_db_memory_stats(inner)?;
out.db.insert(db, parsed);
} else {
parse_memory_stat_field(&mut out, key, &chunk[1])... | Rust | 0 |
# coding=utf-8
# Copyright 2022 The SimREC Authors. 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... | Python | 1 |
_port != p0f::HTTP_PORT && dest_port != p0f::HTTPS_PORT
|| tcp_header.syn() == 0
|| tcp_header.ack() != 0
{
return false;
}
// set IPv4 header signature
tcp_sig.ip_ver = 0x04;
tcp_sig.ttl = ip_header.ttl;
tcp_sig.ip_opt_len = header_len.saturating_sub(20) as u8;
tcp_... | Rust | 0 |
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
mini = math.inf
maxi = -math.inf
flag = False
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
flag = True
if flag:
mini = min(mini, nums[i])
flag = False
for i in reversed(range(len(n... | Python | 1 |
import itertools
import torch
from torch.utils.data import DataLoader,Dataset
import random
import os
from utils import Transform
from torch.nn.utils.rnn import pad_sequence
import numpy as np
from tqdm import tqdm
class Data_Func_S(Dataset):
def __init__(self, data, mode, ind,whole):
super(Data_Func_S... | Python | 1 |
{
gtk::init().expect("Cannot initialize GTK.");
let result = Dictionary::new(DICTIONARIES);
if let Err(error) = result {
show_error_dialog(id, error);
}
let ui = new_ui(id, result.unwrap());
let include = connect_delete_text(SetType::Included, &ui);
... | Rust | 0 |
remove_element(nums: &mut Vec<i32>, val: i32) -> i32 {
if nums.len() == 0 {
return 0;
}
let mut i: usize = 0; //index in vector
let mut k: usize = 0; // length of the new array
loop {
if nums[i] != val {
nums[k] = nums[i];
k = k + 1;
}
i = ... | Rust | 0 |
import numpy as np
from numba import njit
from building3d.geom.points import are_points_coplanar
from building3d.geom.points import is_valid_pt
from building3d.geom.points import points_equal
from building3d.geom.points.intersections import line_segment_intersection
from building3d.geom.types import FLOAT
from buildin... | Python | 1 |
sion::Tls1_2, Some(Version::Tls1_2)),
TestConfig::new(Version::Tls1_0, Version::Tls1_2, Version::Tls1_0, Version::Tls1_2, Some(Version::Tls1_2)),
TestConfig::new(Version::Tls1_2, Version::Tls1_2, Version::Tls1_0, Version::Tls1_2, Some(Version::Tls1_2)),
TestConfig::new(Version::Tls1_... | Rust | 0 |
self.current_card.priority = priority;
},
_ => return Err(ParsingError::Other("unknown key")),
}
},
// TODO: Somehow, this is not unreachable. Try to parse a random file.
ParserState::Flushed => unreachable!(),
... | Rust | 0 |
ex"), not(feature = "no_xop")))]
#[rustfmt::skip]
static OP_HX_EAX_R15_D: OpHx = OpHx {
reg_lo: Register::EAX,
reg_hi: Register::R15D,
};
#[cfg(not(feature = "no_vex"))]
#[rustfmt::skip]
static OP_HX_K0_K7: OpHx = OpHx {
reg_lo: Register::K0,
reg_hi: Register::K7,
};
#[cfg(any(not(feature = "no_vex"), not(feature =... | Rust | 0 |
{
use super::*;
use crate::peer::PeerId;
use std::convert::TryFrom;
const CONFIGURATION_PATH: &str = "tests/test_config.json";
#[test]
fn parse_example_json() -> Result<(), String> {
let configuration = Configuration::from_path(CONFIGURATION_PATH)
.map_err(|e| format!("Fai... | Rust | 0 |
# spikeball/models/tournament.py
from datetime import datetime
from spikeball.extensions import db
class Tournament(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), unique=True, nullable=False)
status = db.Column(db.String(50), default='setup')
created_at = db.Co... | Python | 1 |
<&'a str>>,
pub class: Option<flatbuffers::WIPOffset<&'a str>>,
}
impl<'a> Default for WoffMetadataVendorArgs<'a> {
#[inline]
fn default() -> Self {
WoffMetadataVendorArgs {
name: None, // required field
url: None,
dir: None,
class: None,
}
}
}
pub struct WoffMetadataVendorBuil... | Rust | 0 |
unconditional_guidance_scale=unconditional_guidance_scale,
unconditional_conditioning=unconditional_conditioning,
dynamic_threshold=dynamic_threshold,
encode=encode)
... | Python | 1 |
# 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, software
# distributed un... | Python | 1 |
d, loc, scale = 0, np.inf, 3, 1
lower = (low_bound - loc) / scale
upper = (up_bound - loc) / scale
a = truncnorm.rvs(a=lower,
b=upper,
loc=loc,
scale=scale)
bias = RNG.beta(5, 5)
bias_s = RNG.beta(1, 4... | Python | 1 |
type Target = crate::FieldReader<bool, TEXC_INT_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `TEXC_INT` writer - Interrupt Flag For High Priority Trigger Exception"]
pub struct TEXC_INT_W<'a> {
w: &'a mut W,
}
impl<'a> TEXC_INT_W<'a> {
#[doc = r"Writes... | Rust | 0 |
ders)
//.gzip(true)
.connect_timeout(std::time::Duration::from_secs(30))
//.h2_prior_knowledge()
.build()
.unwrap()
}
trait UrlsInto {
fn urls_into(&self, urls: &mut Vec<String>);
}
impl<T: UrlsInto> UrlsInto for Arc<T> {
fn urls_into(&self, urls: &mut Vec<String>) {
... | Rust | 0 |
img: row.get(3),
time: row.get(4),
date: row.get(5),
postid: row.get(6)
}
);
}
if posts.is_empty() {
return None;
}
Some(posts)
}
// retrieve all posts ('Post').
pub fn retrieve_all_posts() -> Vec<Post> {
let mut ... | Rust | 0 |
#!/usr/bin/python3
"""Rectange class"""
class Rectangle:
"""Rectange"""
pass
| Python | 1 |
def test_movie_official_sites_should_be_a_list(ia):
movie = ia.get_movie('0133093', info=['official sites']) # Matrix
official_sites = movie.get('official sites', [])
assert len(official_sites) == 3
def test_movie_official_sites_if_none_should_be_excluded(ia):
movie = ia.get_movie('1863157', info=[... | Python | 1 |
urn None
pcm_mix = pcm_mix.to(torch.float)
if sample_rate_mix != self.resample_rate:
pcm_mix = torchaudio.transforms.Resample(
orig_freq=sample_rate_mix, new_freq=self.resample_rate
)(pcm_mix)
pcm_enroll = pcm_enroll.to(torch.float)
if sample_rate... | Python | 1 |
import requests
from datetime import timedelta
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.utils.dates import days_ago
default_args = {
"owner": "airflow",
"depends_on_past": False,
"start_date": days_ago(2),
"email": ["airflow@example.com"],
"email... | Python | 1 |
()
#super(cls, cls).setup_class_()
#CheckTuckeyHSD.setup_class_()
cls.meandiff2 = sas_['mean']
cls.confint2 = sas_[['lower','upper']].astype(float).values.reshape((3, 2))
cls.reject2 = sas_['sig'] == asbytes('***')
class TestTuckeyHSD4(CheckTuckeyHSDMixin):
@classmethod
... | Python | 1 |
from django.urls import path
from switchkeys.views.environments import (
AddEnvironmentUserAPIView,
RemoveEnvironmentUserAPIView,
BaseProjectEnvironmentApiView,
DeleteEnvironmentFeatureAPIView,
ProjectEnvironmentApiView,
ProjectEnvironmentKeyApiView,
BaseEnvironmentFeatureAPIView,
Updat... | Python | 1 |
: 'Tiếng Rohingya', 'yo': 'Èdè Rohinga', 'yue': '羅興亞文', 'yue-Hans': '罗兴亚文', 'yue-Hant': '羅興亞文', 'zh': '罗兴亚语', 'zh-Hans': '罗兴亚语', 'zh-Hant': '羅興亞文', 'zu': 'Rohingya'},
'rhp': {'en': 'Yahang'},
'ria': {'en': 'Riang (India)'},
'rie': {'en': 'Rien'},
'rif': {'ast': 'rifianu', 'cs': 'rífština', 'de': 'Tarifi... | Python | 1 |
Some(entry) = stats.ngrams.get_mut(&ngram) {
entry.occurrence_count += 1;
} else {
let ngram = ngram.to_ngram();
let entry = TextColumnStatsNGramEntry {
row_count: 0,
occurrence_count: 1,
};
stats.ngrams.insert(ngram, entry);
}
ngrams_for_row.insert(ngram);
}
for ... | Rust | 0 |
import logging
logger = logging.getLogger(__name__)
from config.config import DEBUG
if DEBUG:
from controllers.Keithley_smu import DummyKeithley_smu as Keithley_smu
else:
from controllers.Keithley_smu import Keithley_smu
from enum import Enum
class OutputMode(Enum):
"""
VOLTAGE
CURRENT
"""
... | Python | 1 |
ement> = {
# <sid_block?>,
# <principal_block?>,
# <effect_block>,
# <action_block>,
# <resource_block>,
# <condition_block?>
# }
# <sid_block?>,
def test_stmt_sid_true(response_03):
assert "Sid" in response_03["Statement"]
assert iam.Policy(**response_03)
def test_stmt_sid_fals... | Python | 1 |
let json_output = serde_json::to_string(&packages)?;
println!("{}", json_output);
}
}
Ok(())
}
pub(crate) fn setup_error_handlers() -> Result<()> {
if tracing::dispatcher::has_been_set() {
return Ok(());
}
let error_layer = ErrorLayer::default();
let filter_... | Rust | 0 |
error: {}", e),
}
}
}
use std::cell::RefCell;
use std::net::{SocketAddr, ToSocketAddrs};
use std::time::Duration;
use mco::net::TcpStream;
use codec::{BinCodec, Codec, Codecs};
use stub::ClientStub;
use mco::std::errors::Result;
use serde::de::DeserializeOwned;
use serde::Serialize;
use balance::RpcClient;
... | Rust | 0 |
ons::TypedUsize,
crypto_tools::{
constants,
k256_serde::{self, SecretScalar},
},
gg20::sign::SignShareId,
sdk::api::{TofnFatal, TofnResult},
};
use ecdsa::{
elliptic_curve::{sec1::FromEncodedPoint, Field},
hazmat::FromDigest,
};
use serde::{Deserialize, Serialize};
use sha2::{Dig... | Rust | 0 |
pred_4 = val_y_pred[val_y_pred.store_code=='4']
val_y_pred_5 = val_y_pred[val_y_pred.store_code=='5']
print "all cost:",cal_cost(val_y_pred_all.y,val_y_pred_all.pred,val_y_pred_all.a,val_y_pred_all.b)
print "1 cost:",cal_cost(val_y_pred_1.y,val_y_pred_1.pred,val_y_pred_1.a,val_y_pred_1.b)
print "2 cost:",cal_cost(val_y... | Python | 1 |
import os
import sys
model_path = './model'
model_exists = False
if not os.path.exists(model_path):
print('Model does not exist. First run <training.py>')
thetas = {'theta0': 0, 'theta1': 0}
else:
model_exists = True
thetas = {}
with open(model_path, 'r') as file:
content = file.read()
lines = content.split(... | Python | 1 |
# era_msd.py
# Johannes Kaisinger, 4 July 2024
#
# Demonstrate estimation of State Space model from impulse response.
# SISO, SIMO, MISO, MIMO case
import numpy as np
import matplotlib.pyplot as plt
import os
import control as ct
# set up a mass spring damper system (2dof, MIMO case)
# Mechanical Vibrations: Theory ... | Python | 1 |
enough participants"))
.1
}
#[cfg(test)]
mod tests {
use super::*;
fn testing(st: &str, we: Vec<i32>, n: usize, exp: &str) -> () {
assert_eq!(rank(st, we, n), exp)
}
#[test]
fn basics_rank() {
testing(
"Addison,Jayden,Sofia,Michael,Andrew,Lily,Benjamin",
... | Rust | 0 |
");
}
#[tokio::test]
async fn test_graph_transpile_user_config() {
let specifier = resolve_url_or_path("https://deno.land/x/transpile.tsx")
.expect("could not resolve module");
let (mut graph, handler) = setup(specifier).await;
let config_file =
ConfigFile::read("tests/module_graph/tsconf... | Rust | 0 |
ame>juliotpaez/arangodb-types
use std::fmt;
use std::marker::PhantomData;
use std::str::FromStr;
use serde::de::Visitor;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
/// The id of a collection.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct DBId<K, C> {
key: K,
collection: C,
}
... | Rust | 0 |
AreaChartColumn(
"Last 12 Months",
width="large",
help="Open Price for the last 12 Months",
),
},
hide_index=True,
height=250,
use_container_width=True,
)
ticker_df, history_dfs = downlo... | Python | 1 |
plied_transform" in meta:
applied_transform = torch.tensor(meta["applied_transform"], dtype=transform_matrix.dtype)
transform_matrix = transform_matrix @ torch.cat(
[applied_transform, torch.tensor([[0, 0, 0, 1]], dtype=transform_matrix.dtype)], 0
)
if "applie... | Python | 1 |
config_path(&self) -> &Arc<Option<PathBuf>> {
&self.config_path
}
}
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub struct AsyncItemHandle(u32);
entity_impl!(AsyncItemHandle, "async_item");
// The ABI uses distinct entity types for each kind of async item because most host calls ope... | Rust | 0 |
common = var*four_over_tau/np.sqrt((X_prod[:,None]+1.)*(X2_prod[None,:]+1.)-np.square(XTX))*dL_dK
if self.ARD:
if X2 is not None:
XX2 = X[:,None,:]*X2[None,:,:] if X2 is not None else X[:,None,:]*X[None,:,:]
XX = np.square(X)
X2X2 = np.square(X2)
... | Python | 1 |
tps://www.gnu.org/software/bc/'
aliases = ['bc']
filenames = ['*.bc']
version_added = '2.1'
tokens = {
'root': [
(r'/\*', Comment.Multiline, 'comment'),
(r'"(?:[^"\\]|\\.)*"', String),
(r'[{}();,]', Punctuation),
(words(('if', 'else', 'while', 'fo... | Python | 1 |
import numpy as np
import random
import torch
def set_seed(seed: int, deterministic: bool = False):
"""
Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch`.
Args:
seed (`int`):
The seed to set.
deterministic (`bool`, *optional*, defaults to ... | Python | 1 |
from eli5.sklearn import PermutationImportance
import eli5
from sklearn import neighbors
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
import... | Python | 1 |
import numpy as np
import cv2 as cv
import torch
color_map = np.array(
[
[0, 0, 0], # unlabeled black
[255, 120, 50], # barrier orange
[255, 192, 203], # bicycle pink
[255, 255, 0], # bus yellow
[0, 1... | Python | 1 |
let empty = String::from(EMPTY);
format!(
"dev={}, id={}",
bdm.device_name.as_ref().unwrap_or(&empty),
bdm.ebs
.as_ref()
.unwrap()
.volume_id
.as_ref()
.unwrap_or(&empty),
)
}
fn iam_instance_profile_to_string(iip: &ec2::IamIn... | Rust | 0 |
ata does not match, bad-hex: {:02x?}",
&serialized.1[..]
);
assert_eq!(
uper,
&deserialize_uper::<T>(data, bits),
"Deserialized data struct does not match"
);
}
#[cfg(feature = "protobuf")]
pub fn serialize_protobuf(to_protobuf: &impl Writable) -> Vec<u8> {
let mut write... | Rust | 0 |
Return a fake update task signature and its serialized version
pub fn update_task_signature() -> (Signature, Vec<u8>) {
let bytes = vec![0x44; 64];
let signature = Signature::from_slice(&bytes[..]).unwrap();
(signature, bytes)
}
/// Return a local seed dictionary with two entries w... | Rust | 0 |
TWORK_STATE";
const CONTAINER_ADDRESS_STORAGE_KEY: &[u8] = b"CONTAINER_ADDRESS";
const DEFAULT_NETWORK: &str = "172.24.0.0/16";
const DEFAULT_BRIDGE: &str = "knast0";
type ContainerAddressStorage = BTreeMap<String, (String, Ipv4Addr, Ipv4Addr)>;
#[fehler::throws]
pub fn setup(
storage: &Storage<impl StorageEngine... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.