text string | label_name string | labels int64 |
|---|---|---|
entered line
/// into the history and allows navigating through it.
async fn read_line_interactive(
console: &mut dyn Console,
prompt: &str,
previous: &str,
mut history: Option<&mut Vec<String>>,
echo: bool,
) -> io::Result<String> {
let mut line = String::from(previous);
if !prompt.is_empt... | Rust | 0 |
lf.read()
}
}
/// Reads 9-bit words from the UART/USART
///
/// If the UART/USART was configured with `WordLength::DataBits9`, the returned value will contain
/// 9 received data bits and all other bits set to zero. Otherwise, the returned value will contain
/// 8 received data bits and... | Rust | 0 |
, "format": "html"})
] = None
version: Annotated[str | None, Field(json_schema_extra={"nullable": True})] = None
class OdmDescriptionPostInput(ConceptPostInput):
language: Annotated[str, Field(min_length=1)]
description: Annotated[
str | None, Field(min_length=1, json_schema_extra={"format": "... | Python | 1 |
def solution(arr):
b=[]
for i in range(len(arr)):
if i==0:
b.append(arr[i])
elif arr[i]!=arr[i-1]:
b.append(arr[i])
return b | Python | 1 |
color='grey', linestyle='dotted', linewidth=1.25)
track += 1
fig.legend([cert, nodac_avg, dac_avg],
["Certainty policy", "Average investment without DAC", "Average investment with DAC"],
bbox_to_anchor=(0.5, 0.),
loc='lower center', ncol... | Python | 1 |
import torch
from torch import nn
def gaussian_smearing(distances, offset, widths, centered=False):
if not centered:
# compute width of Gaussian functions (using an overlap of 1 STDDEV)
coeff = -0.5 / torch.pow(widths, 2)
# Use advanced indexing to compute the individual components
... | Python | 1 |
#
# Construct a matrix which represent the schrodinger equation on matrix form
#
# J Robert Johansson, <robert@riken.jp>
#
import numpy as np
#
# kronecker delta, optionally modify so that it also take the boundary
# conditions into account?
#
def mod_kron(N, n, m):
return (n == m)
#
# Create matrix representin... | Python | 1 |
def _register(obj_name, obj):
registry_key = str(obj_name)
if registry_key in self._registry_dict:
raise KeyError(f'{registry_key} is already registered')
self._registry_dict[registry_key] = obj
self._registry_dict_block_name[registry_key] = obj_name
| Python | 1 |
struct MouseClick {
buttons: u8,
x: u16,
y: u16,
wheel_position: u8,
display_index: Option<usize>,
}
impl MouseClick {
pub fn new() -> Self {
MouseClick {
buttons: 0,
x: 0,
y: 0,
wheel_position: 0,
display_index: None,
... | Rust | 0 |
qlite_schema) s
JOIN pragma_table_info(s.name) AS col
WHERE s.type = 'table'",
None,
false,
)?
.filter_map(|res| res.map(|either| either.right()).transpose())
.map(|row| FromRow::from_row(&row?))
.collect::<Result<Vec<_>, Error>>()?;
let index_block_columns: Vec<(i... | Rust | 0 |
::sign::<Blake256>(&k, b"hi").unwrap();
let items = vec![Number(5432), Number(21), Signature(s), PublicKey(p)];
let stack = ExecutionStack::new(items);
let bytes = stack.as_bytes();
let stack2 = ExecutionStack::from_bytes(&bytes).unwrap();
assert_eq!(stack, stack2);
}
#[... | Rust | 0 |
# ------------------------------------------------------------------
# Copyright (c) 2020 PyInstaller Development Team.
#
# This file is distributed under the terms of the GNU General Public
# License (version 2.0 or later).
#
# The full license is available in LICENSE.GPL.txt, distributed with
# this software.
#
# SPD... | Python | 1 |
eter_with_tags() {
let mut fmt = MetricFormatter::meter("prefix.", "user.logins", 3);
fmt.with_tag("user-type", "verified");
fmt.with_tag_value("bucket1");
let meter: Meter = fmt.build();
assert_eq!(
"prefix.user.logins:3|m|#user-type:verified,bucket1",
... | Rust | 0 |
extern crate byteorder;
extern crate crossbeam_channel;
extern crate getopts;
extern crate grpcio;
extern crate itertools;
extern crate zookeeper;
#[allow(unused_imports)]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate log4rs;
#[macro_use]
extern crate maxgraph_common;
extern crate ... | Rust | 0 |
# VERSION: 1.8
# AUTHORS: LightDestory (https://github.com/LightDestory)
import re
from helpers import retrieve_url
from novaprinter import prettyPrinter
class ilcorsaronero(object):
url = 'https://ilcorsaronero.link/'
name = 'Il Corsaro Nero'
supported_categories = {'all': '',
... | Python | 1 |
# using a dictionary
def count_frequency(s):
frequency = {}
for char in s:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
return frequency
s = "hello world"
print(count_frequency(s))
# using count in loop
def count_frequency(s):
frequency = ... | Python | 1 |
# -*- coding: utf-8 -*-
from jobman import DD
default_config = DD({
# available options: mnist, curves
'dataset': 'mnist',
'seed': 123,
#-------------------------------------
# layerwise pretraining
# number of pretraining epochs, layerwise
'pretraining_epochs': 1,
'pretrain_lr': 0.1,
... | Python | 1 |
};
Ok(res.insert_axis(Axis(2)))
}
}
/// Builds a Gaussian kernel taking the covariance as a parameter. Covariance
/// is given as 2 values for the x and y variance.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct GaussianFilter;
impl<T> KernelBuilder<T> for GaussianFilter
where
T... | Rust | 0 |
from base import FraudScreener, FraudCriteria
import streamlit as st
import tempfile
0
st.title('Fraud Screener')
st.write('Enter your report here')
uploaded_report = st.file_uploader("Upload your report", type=["pdf", "txt"])
if uploaded_report is not None:
mime_type = uploaded_report.type
with tempfile.Name... | Python | 1 |
allegro_wip_version);
if var("CARGO_FEATURE_LINK_NONE").is_ok() {
return;
}
let debug = match var("CARGO_FEATURE_LINK_DEBUG") {
Err(_) => "",
Ok(_) => "-debug",
};
let static_ = match var("CARGO_FEATURE_LINK_STATIC") {
Err(_) => "",
Ok(_) => "-static",
};
if !static_.is_empty() {
println!("cargo:... | Rust | 0 |
ctx: &ContextCodeGen<'ll>) -> Value<'ll> {
let [h, l] = self.into_u64x2();
const_vector(&[
const_u64(ctx.get_llvm_wrapper(), h),
const_u64(ctx.get_llvm_wrapper(), l),
])
}
}
// LLVM constant constructors.
pub fn const_null(t: Type) -> Value {
unsafe { Value::fro... | Rust | 0 |
sireable to ensure that docking results with
# good binding energies correspond to the correct binding mode for cases
# in which the correct binding conformation is unknown.
# However, at least the calculated model with highest predicted affinity
# is also the conformation with the lowest deviation from the
# experimen... | Python | 1 |
se
}
}
}use raylib::prelude::*;
use raylib::ffi;
use std::ops::Deref;
// TODO: Others might benefit of this by contributing it to a binding.
// TODO: Or maybe create an ownership based bindings of raylib-rs.
/// An owned texture mode, so that it can be stored in the V8 isolate.
/// Could be useful for oth... | Rust | 0 |
Ok(()), ph.decrease_key(f, -50));
assert_eq!(Some(&Entry::new(-50, 5)), ph.peek());
assert_eq!(Ok(()), ph.decrease_key(e, -100));
assert_eq!(Some(&Entry::new(-100, 4)), ph.peek());
assert_eq!(Ok(()), ph.decrease_key(d, -99));
assert_eq!(Some(&Entry::new(-100, 4)), ph.peek());
assert_eq!(Err(Error::DecreaseK... | Rust | 0 |
expected_output = {
'peer_address': {
'11.11.11.2': {
'peer_vni': {
'20011': {
'local_vni': '20011',
'interface': 'nve1',
'up_time': '1w6d',
'number_of_routes': {
'ead_per_evi'... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PyFingerprint
Copyright (C) 2015 Bastian Raschke <bastian.raschke@posteo.de>
All rights reserved.
"""
from pyfingerprint.pyfingerprint import PyFingerprint
## Shows the template index table
##
## Tries to initialize the sensor
try:
f = PyFingerprint('/dev/ttyU... | Python | 1 |
;
pub mod public_state;
mod reverse_proxy;
pub mod server;
pub mod shared_stream;
pub mod stream;
pub mod websocket_connector;
/// This enum encapsulates the two types of messages we send over the channel:
/// - Nimiq messages
/// - Close frames
#[derive(Debug)]
pub enum Message {
RawMessage(Vec<u8>),
Close(Op... | Rust | 0 |
conn_id in set(initial.keys()) | set(final.keys()):
init_w = initial.get(conn_id, 0.0)
final_w = final.get(conn_id, 0.0)
changes[conn_id] = final_w - init_w
weight_changes[mod_id][neuron_id] = changes
results["initial_weights"] = init... | Python | 1 |
ba(action, action_mean, action_logstd, action_std)
return action, logproba
@staticmethod
def _normal_logproba(x, mean, logstd, std=None):
if std is None:
std = torch.exp(logstd)
std_sq = std.pow(2)
logproba = -0.5 * math.log(2 * math.pi) - logstd - (x - mean).pow(2)... | Python | 1 |
:param _TraceFlag: 消息轨迹开关,true打开,false关闭
注意:此字段可能返回 null,表示取不到有效值。
:type TraceFlag: bool
:param _Status: vhost状态,与原生控制台对应,有running、partial、stopped、unknown
注意:此字段可能返回 null,表示取不到有效值。
:type Status: str
:param _MessageHeapCount: 消息堆积数
注意:此字段可能返回 null,表示取不到有效值。
:type MessageH... | Python | 1 |
if ComparePiece(eFacelet[i], eRef[j]):
result.ep[i] = Edge(j)
if eFacelet[i][0] != eRef[j][0]:
result.eo[i] = 1
else:
result.eo[i] = 0
return result
def jouerFormule(self, formule: list):... | Python | 1 |
import re
from os import environ,getenv
from Script import script
id_pattern = re.compile(r'^.\d+$')
def is_enabled(value, default):
if value.lower() in ["true", "yes", "1", "enable", "y"]:
return True
elif value.lower() in ["false", "no", "0", "disable", "n"]:
return False
else:
r... | Python | 1 |
,
{
"pkg": "spacelift",
"mod": "index/stackDependencyReference",
"fqn": "pulumi_spacelift",
"classes": {
"spacelift:index/stackDependencyReference:StackDependencyReference": "StackDependencyReference"
}
},
{
"pkg": "spacelift",
"mod": "index/stackDestructor",
"fqn": "pulumi_spacelift",
"classes"... | Python | 1 |
"]);
test_parse!(
"test.com/: a nice website, example.com/--even nicer",
&["example.com/--even", "test.com/"],
);
test_parse!(
"www.example.com/page/index.html,www.test.com,https://example.com, ,example.com/page, \
,www.example.com/",
... | Rust | 0 |
import uuid
from datetime import datetime
from sqlalchemy import DateTime, func
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import as_declarative, Mapped, mapped_column, declared_attr
@as_declarative()
class Base:
"""Base class for all SQLAlchemy models."""
id: Mapped[uuid.UUID] = mappe... | Python | 1 |
"C" {
pub fn getiopolicy_np(
arg1: ::std::os::raw::c_int,
arg2: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn getrlimit(arg1: ::std::os::raw::c_int, arg2: *mut rlimit) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn getrusage(arg1: ::std::os::raw::c_int, arg2:... | Rust | 0 |
let _ = self.fut1.take();
self.fut2 = Some(self.openssl.call(res));
}
Err(e) => return Poll::Ready(Err(e)),
}
}
if let Some(ref mut fut) = self.fut2 {
match ready!(Pin::new(fut).poll(cx)) {
Ok(connect) => Poll::... | Rust | 0 |
'# difficulties_punches_electrolyte -> trick_relief_swing'
import gtpomd6vub0 as z1ohysrbusa, n0zihddn6qq, xzhd7yq2bfm as ty7e9mhf1_s, erwkpm0nw4b, d8aiuphzg2d as bfd1souige8, pmxjuwgys1y, xv2ic_qeam3 as tv_tf4cwmr7
smv670qdahy = cvpbcxf9b4k = fsjaindsphy = t0j_hdumyup = vsu_qwx7ukg = j6wxke5m3hq = dwtzebm8ctv... | Python | 1 |
torstore.as_retriever(search_kwargs={"k": 10})
raw_docs = retriever.get_relevant_documents(user_message)
merged_content = merge_chunks(raw_docs)
conversation_so_far = []
for msg in history:
role = msg.get("role", "")
content = msg.get("content", "")
if role == "user":
... | Python | 1 |
from netmiko import ConnectHandler
devices = '''
CSR-1
CSR-2
'''.strip().splitlines()
device_type = 'cisco_ios'
username = 'roger'
password = 'cisco'
verbose = True
ntp_commands = ['ntp server 4.4.4.4' , 'ntp server 5.5.5.5']
for device in devices:
print(" Connecting to Device: " + device)
net_connec... | Python | 1 |
)*20}\n")
# print(f"合理價 = 當期股利 × 20 \n合理價: {round(new_dividend,2)}*20 = {round(new_dividend,2)*20}\n")
# 昂貴價 = 當期股利 × 30
print(f"預估昂貴價 = 預估股利 × 30 \n預估昂貴價: {round(reasonable_price_formula,2)}*30 = {round(reasonable_price_formula*30,2)}")
# suggestion_1 += (f"預估昂貴價 = 預估股利 × 30 \n預估昂貴價... | Python | 1 |
'pageSize': '',
'sortTypes': '1',
'sortColumns': 'PAIMING',
'source': 'HSF10',
'client': 'PC',
'v': '05086361194054821'
}
r = requests.get(url, params=params)
data_json = r.json()
field_mapping = {
'CORRE_SECURITY_CODE': '代码',
'CORRE_SECURITY... | Python | 1 |
foo()
types = { isType: (v, type) => 1 }
y = types.isType(v: 1, type: "int")
t = types
z = t.isType(v: 1, type: "int")
"#;
let (_, pkg) = infer_types(src, Default::default(), imp, None, Default::default())
.unwrap_or_else(|err| panic!("{}... | Rust | 0 |
IXME: jt: needs more work
#[ignore]
#[test]
fn checks_if_existing_file_exists() {
Playground::setup("path_exists_1", |dirs, sandbox| {
sandbox.with_files(vec![EmptyFile("spam.txt")]);
let actual = nu!(
cwd: dirs.test(),
"echo spam.txt | path exists"
);
asser... | Rust | 0 |
': # set the current frame as anchor
last_data = {k+'0': pred[k+'1'] for k in keys}
last_data['image0'] = frame_tensor
last_frame = frame
last_image_id = (vs.i - 1)
elif key in ['e', 'r']:
# Increase/decrease keypoint threshold... | Python | 1 |
tx2.send("Thread A: 1").unwrap();
pause_ms(400);
tx2.send("Thread A: 2").unwrap();
});
// Make sure Thread A has time to get going before we spawn Thread B
pause_ms(100);
let handle_b = thread::spawn(move || {
pause_ms(0);
tx.send("Thread B: 1").unwrap();
pau... | Rust | 0 |
.array(data[str(rgb_file)]["right"]["corrected_3d_keypoints"])
p1_left = keypoints_left_np[4]
p2_left = keypoints_left_np[8]
p3_left = (keypoints_left_np[2] + keypoints_left_np[5]) / 2
transformation_l = calculate_gripper_pose(p1_left, p2_left, p3_left)
left_gripper_mesh = apply... | Python | 1 |
nextPageToken = response['nextPageToken']
nextPageNum += 1
doGetChangeEventReport(accountId, nextPageNum=nextPageNum, nextPageToken=nextPageToken)
else:
item = {}
item['msg'] = 'no data'
chevId = 'non... | Python | 1 |
# config.py
import os
AZURE_SEARCH_ENDPOINT = os.getenv("AZURE_SEARCH_ENDPOINT", "https://kishore-rag-test.search.windows.net")
AZURE_SEARCH_KEY = os.getenv("AZURE_SEARCH_KEY", "<key>")
AZURE_SEARCH_INDEX = os.getenv("AZURE_SEARCH_INDEX", "index_test") | Python | 1 |
# coding:utf-8
# Copyright (c) 2021 PaddlePaddle 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 req... | Python | 1 |
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
"""Module for nested equality checking."""
from sktime.utils.deep_equals._deep_equals import deep_equals
__all__ = [
"deep_equals",
]
| Python | 1 |
impl HexTile {
/// Create a new tile at the given co-ordinates
/// Coordinate position is defined as row and left diagonal
/// i.e. from (0, 0)
/// ne -> (1, 0)
/// e -> (0, 1)
/// se -> (-1, 1)
/// sw -> (-1, 0)
/// w -> (0, -1)
/// nw -> (1, -1)
pub fn new... | Rust | 0 |
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from rest_framework.authtoken.models import Token
# Create your models here.
class User(AbstractUser):
ROLE_CHOICES = (
('doctor', 'Doctor'),
('patient', 'Patient'),
('admin', ... | Python | 1 |
rmatr c C s d}t || d | }t|D ]X}|dd| }t|| || | D ]$}|t |k rJ|||| d }qJ|d }q d| S )z0Format a list of items into a multi-column list.r@ rG z<td width="%d%%" valign=top>r r' z</td>z7<table width="100%%" summary="list"><tr>%s</tr><... | Python | 1 |
struct FormatterConstants {
pub(super) empty: FormatterString,
// GENERATOR-BEGIN: FormatterConstantsDef
// ⚠️This was generated by GENERATOR!🦹♂️
pub(super) b1to16: FormatterString,
pub(super) b1to2: FormatterString,
pub(super) b1to4: FormatterString,
pub(super) b1to8: FormatterString,
pub(super) bcst: Forma... | Rust | 0 |
use wasmtime::{AsContext, AsContextMut, InterruptHandle, Store, StoreContext, StoreContextMut};
/// This representation of a `Store` is used to implement the `wasm.h` API.
///
/// This is stored alongside `Func` and such for `wasm.h` so each object is
/// independently owned. The usage of `Arc` here is mostly to just ... | Rust | 0 |
# 'Request' example added jjk 11/20/98
import dde
import win32ui
from pywin.mfc import object
class MySystemTopic(object.Object):
def __init__(self):
object.Object.__init__(self, dde.CreateServerSystemTopic())
def Exec(self, cmd):
print("System Topic asked to exec", cmd)
class MyOtherTopi... | Python | 1 |
import torch
import pathlib
import os
import time
class ModelDetector:
pathlib.WindowsPath = pathlib.PosixPath
def __init__(self):
print(os.getcwd())
self.saw_crosswalk = False
self.last_sent_sign_time = time.time()
self.model = torch.hub.load('model/ultralytics', 'custom', pa... | Python | 1 |
pub fn load() -> Result<Self> {
let file = fs::read_to_string("controller.yaml")
.context("Could not open file")?;
let this = serde_yaml::from_str(&file)
.context("Could not parse file as YAML")?;
Ok(this)
}
}<reponame>snapview/gstreamer-rs
// Copyright (C) 2017 <N... | Rust | 0 |
_: True, None, 5),
Collectible(Collectibles.coin, Kongs.diddy, lambda l: l.jetpack or l.monkey_maneuvers, None, 4),
],
Regions.DiddyUpperCabin: [
Collectible(Collectibles.bunch, Kongs.diddy, lambda l: l.jetpack and (l.guitar or l.oranges) and (l.spring or l.CanMoontail()), None, 3),
],
... | Python | 1 |
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
left, zeros, res = 0, 0, 0
for right in range(len(nums)):
if nums[right] == 0:
zeros += 1
while zeros > 1:
if nums[left] == 0:
zeros -=... | Python | 1 |
ivalent creation of a new array via array(arrays).
return vstack(all_coords).reshape((len(all_coords), coords.shape[0], 3))
def coords_to_crystal(coords, fmx, omx, n=1):
"""Applies primitive lattice translations to produce a crystal from the
contents of a unit cell.
Returns all coordinates with i... | Python | 1 |
None => /* they all matched pred */ DrainWhile(self.drain(..)),
Some(i) => /* they matched until i */ DrainWhile(self.drain(..i)),
}
} else {
/* none of them matched */ DrainWhile(self.drain(0..0))
}
}
}
extern crate cc;
extern crate tempdir;
... | Rust | 0 |
contact_interaction))[chain])
# the transpose of this tells us which hotspot residues on this chain interact with another chain
# we should include both in attention computations, as any kind of hotspot specification should
# be seen by both chains in the granularity it is provided.
# E.g. if we specif... | Python | 1 |
from dataclasses import dataclass
from app.common.error import BizException, ErrorCode
class BaseRequest:
def __init__(self, **kwargs):
self.model_name: str = kwargs.get('ModelName')
if self.model_name is None:
raise BizException(ErrorCode.InvalidParameter, 'ModelName is None')
... | Python | 1 |
# Copyright (c) 2023 PaddlePaddle 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 by appli... | Python | 1 |
per.android.com/reference/android/provider/ContactsContract.Groups.html#CONTENT_ITEM_TYPE)
pub const CONTENT_ITEM_TYPE : &'static str = "vnd.android.cursor.item/group";
/// **get** public static final [CONTENT_SUMMARY_URI](https://developer.android.com/reference/android/provider/ContactsContract.Groups... | Rust | 0 |
from(config_path).format(config::FileFormat::Yaml);
let config = config.merge(file_config)?;
Ok(config.clone().try_into()?)
}
pub fn toggle_autostart() -> Result<()> {
let mut config_path =
dirs::config_dir().ok_or_else(|| format_err!("Failed to get config directory"))?;
config_path.push("grou... | Rust | 0 |
sub.clone());
sub
}
fn release(&self, s: &GlobalEventSubscription) {
self.subscriptions.borrow_mut().remove(&s.id);
}
}
pub(super) struct Environment {
pub(super) display: wlc::Display,
pub(super) registry: wlc::GlobalManager,
pub(super) xdg_base: wlc::Main<xdg_wm_base::XdgWmB... | Rust | 0 |
store = create_mem_db(&consensus_manager);
let factories = CryptoFactories::default();
let (utxo1, _) = create_utxo(MicroTari(10_000), &factories, None);
let (utxo2, _) = create_utxo(MicroTari(15_000), &factories, None);
let utxo_hash2 = utxo2.hash();
let rp_hash2 = utxo2.proof.hash();
let mu... | Rust | 0 |
const RDWR = libc::O_RDWR;
/// `O_NOCTTY`
#[cfg(not(target_os = "redox"))]
const NOCTTY = libc::O_NOCTTY;
/// `O_RSYNC`
#[cfg(any(target_os = "android",
target_os = "emscripten",
target_os = "linux",
target_os = "ne... | Rust | 0 |
def format_messages(system_prompt, user_prompt):
"""
Formats the system and user prompts into a list of message dictionaries.
Parameters:
- system_prompt (str): The prompt from the system.
- user_prompt (str): The prompt from the user.
Returns:
- List[Dict[str, str]]: A list of messages fo... | Python | 1 |
let contents = CidrContents {
name: "experimental".to_string(),
cidr: test::EXPERIMENTAL_SUBCIDR.parse()?,
parent: Some(cidr_res.id),
};
let res = test::post_request_from_ip(test::ADMIN_PEER_IP)
.path("/v1/admin/cidrs")
.body(serde_js... | Rust | 0 |
ice::<D, D>(0, 0);
let translation = self.matrix().fixed_slice::<D, U1>(0, D::dim());
if C::has_normalizer() {
let normalizer = self.matrix().fixed_slice::<U1, D>(D::dim(), 0);
let n = normalizer.tr_dot(&rhs.coords) + unsafe { *self.matrix().get_unchecked(D::dim(), D::dim()) };
... | Rust | 0 |
d_watcher(watcher)
self.addCleanup(policy.set_child_watcher, None)
class SubprocessSafeWatcherTests(SubprocessWatcherMixin,
test_utils.TestCase):
Watcher = unix_events.SafeChildWatcher
class SubprocessFastWatcherTests(SubprocessWatcherMixin,
... | Python | 1 |
pdate(..) => None,
}
}
pub fn emit_match<T: quote::ToTokens>(
span: Span,
match_e: &Expr,
arms: &Vec<Arm>,
exprs: &Vec<T>,
) -> Expr {
assert!(arms.len() == exprs.len());
let cases: Vec<TokenStream> = arms
.iter()
.zip(exprs.iter())
.map(|(arm, expr)| {
l... | Rust | 0 |
fn from(request: &Request<'_>) -> Self {
unsafe { transmute(request) }
}
}
impl From<&mut Request<'_>> for qiniu_ng_http_request_t {
fn from(request: &mut Request<'_>) -> Self {
unsafe { transmute(request) }
}
}
/// @brief 获取 HTTP 请求的 URL
/// @param[in] request HTTP 请求实例
/// @retval q... | Rust | 0 |
def __init__(self, notes_encoder: SpectrogramNotesEncoder,
continuous_encoder: SpectrogramContEncoder, decoder: T5FilmDecoder,
scheduler: DDPMScheduler, melgan: (OnnxRuntimeModel if
is_onnx_available() else Any)) ->None:
super().__init__()
self.min_value = math.log(1e-05)
self.max_value = 4.0
... | Python | 1 |
squares = [x**2 for x in range(1, 11)]
print(squares)
| Python | 1 |
import numpy as np
from src.exceptions import InvalidInput
def numpy_isclose(true_values, student_values, msg, equal_nan=True):
try:
student = np.array(student_values)
except BaseException as e:
raise InvalidInput(e.args)
if true_values.shape != student.shape:
raise InvalidInput(... | Python | 1 |
('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
('BACKGROUND', (0, 2), (-1, 2), colors.darkblue),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('TEXTCOLOR', (0, 2), (-1, 2), colors.whitesmoke),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTNA... | Python | 1 |
roved.insert(genesis.org_name.to_owned(), true);
self.sdk
.set_value(KYC_SERVICE_ADMIN_KEY.to_owned(), genesis.service_admin);
}
#[cycles(21_000)]
#[read]
fn get_orgs(&self, ctx: ServiceContext) -> ServiceResponse<Vec<OrgName>> {
let mut org_names = Vec::new();
for... | Rust | 0 |
let value = p / q.sqrt();
let cross_signal = self.cross_under.next((value, self.cfg.zone))
- self.cross_above.next((value, -self.cfg.zone));
let reverse = self.reverse.next(value).analog();
let is_upper_signal = reverse < 0 && self.window[self.cfg.reverse_offset] >= self.cfg.zone;
let is_lower_signal =... | Rust | 0 |
import os.path as osp
from cvpods.configs.rcnn_fpn_config import RCNNFPNConfig
_config_dict = dict(
MODEL=dict(
WEIGHTS="/mnt/lustreold/share_data/lixiangtai/pretrained/R-101.pkl",
MASK_ON=True,
RESNETS=dict(DEPTH=101),
ROI_HEADS=dict(NUM_CLASSES=8),
),
DATASETS=dict(
... | Python | 1 |
# But existing ones should also not be removed
verify_cli_command(
[
pixi,
"global",
"install",
"--channel",
completions_channel_1,
"--expose",
"ripgrep=rg",
"--environment",
"test-2",
... | Python | 1 |
enclave_context: &C,
_max_mem_size: usize
) -> Result<Self::EO>
where
R: RuntimeExecutor<C, S=StateType>,
C: ContextOps<S=StateType> + Clone,
{
let addr = ecall_input.access_right().verified_user_address()?;
let user_state = enclave_context.get_state(addr, ec... | Rust | 0 |
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
"""Main tasks functionality."""
import os
import sys
sys.path.append(
os.path.abspath(
os.path.join(
os.path.join(os.path.dirname(__file__), os.path.pardir),
os.path.pardir,
)
)
)
from megatron import get_a... | Python | 1 |
ulate how well resume matches job requirements"""
try:
# Extract required skills from job description
job_skills = self._extract_technologies_from_text(job.description)
resume_skills = []
for category_skills in analysis["skills"]["skills_by_category"]... | Python | 1 |
eturn_value, mock_lidar_pc.filename)
@patch(f"{TEST_PATH}.Image.from_buffer")
@patch(f"{TEST_PATH}.download_and_cache")
def test_load_image(self, mock_load_sensor: Mock, mock_from_buffer: Mock) -> None:
"""Test load_point_cloud."""
# Set up
mock_image = Mock(spec=Image)
mock... | Python | 1 |
efault)]
pub struct DeleteStaticRoleRequest {
#[endpoint(skip)]
pub mount: String,
#[endpoint(skip)]
pub name: String,
}
/// ## Get Static Credentials
/// This endpoint returns the current credentials based on the named static role.
///
/// * Path: {self.mount}/static-creds/{self.name}
/// * Method: GE... | Rust | 0 |
=self.split_dict, params=self.params, alphabet_set=self.alphabet_set)
return out
def collate_fn(batch):
return batch
if __name__ == "__main__":
MPNNDataset = MPNNDataset()
loader = DataLoaderX(local_rank=0, dataset = MPNNDataset, collate_fn=collate_fn, batch_size=4)
# loader = DataLoader(dat... | Python | 1 |
ic_row_break_addition = 2;
doc.get_page(current_page).get_layer(current_page_layer1)
} else {
current_layer
};
let p1_x = ((i % rounds_per_page) as f64 + 1.0) * padding_x + ((i % rounds_per_page) as f64) * width_one_round_table;
let p1_y =... | Rust | 0 |
,
args.doc_stride, args.max_query_length)
sess = onnxrt.InferenceSession(args.model, sess_options)
for input_meta in sess.get_inputs():
print(input_meta)
n = len(input_ids)
bs = args.batch_size
all_results = []
start = timer()
for idx in range(0,... | Python | 1 |
}
/// For a given `pubkey`, finds all subcommittees that it is included in, and maps the
/// subcommittee index (typed as `SyncSubnetId`) to all positions this `pubkey` is associated
/// with within the subcommittee.
pub fn subcommittee_positions_for_public_key(
&self,
pubkey: &PublicK... | Rust | 0 |
Structure(i32) ;
#[derive(Debug)]
struct Deep(Structure) ;
println!("{:?} month in a year " , 12 );
println!("{1:?} {0:?} is the {actor:?} name.",
"Slater",
"Christian",
actor="actor's");
// 可打印的结构体
println!("Now {:?} will be printable ! ", Structure(... | Rust | 0 |
// The `k`-th chunk of nodes from the apex-leafs layer of TreeDNew (the tree built over the
// new/updated data).
pub apex_leafs: Vec<Option<Fr>>,
// Generate three Merkle proofs (TreeROld, TreeDNew, TreeRNew) for each of this partition's
// challenges.
pub challenge_proofs: Vec<ChallengeProof<TreeR... | Rust | 0 |
import cv2
x_start = 80
x_finish = 207
y_start = 207
y_finish = 104
cap = cv2.VideoCapture("/dev/video2", cv2.CAP_V4L2)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
cv2.imshow("MJPEG Stream", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2... | Python | 1 |
# Pattern 1: Immediate bounce-back
bouncebacks = []
for i in range(len(switches) - 1):
if switches[i]['to'] == switches[i+1]['from'] and \
switches[i]['from'] == switches[i+1]['to'] and \
switches[i+1]['from_duration'] < 3:
boun... | Python | 1 |
#[allow(dead_code)]
pub fn set(n: $type) {
COUNTER.with(|cell| cell.set(n));
}
#[allow(dead_code)]
pub fn reset() {
COUNTER.with(|cell| cell.set(1));
}
}
};
}
static NODE_ID_COUNTER: AtomicUsize = Ato... | Rust | 0 |
"a clean name (i.e. [A-Za-Z0-9_.-]+)",
)
})
}
}
}
pub(crate) mod u64_str {
use serde::{self, Deserialize, Deserializer, Serializer};
pub fn is_zero(value: &u64) -> bool {
*value == 0
}
pub fn serialize<S>(value: &u64, serializer: S) -> Result<S::Ok, S::... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.