text string | label_name string | labels int64 |
|---|---|---|
"""Return information to link this entity with the correct device."""
return {
"manufacturer": MANUFACTURER,
"identifiers": {(DOMAIN, self.device.account_module_index)},
}
def _update_device_data(self):
"""Update the internal data from the coordinator."""
... | Python | 1 |
PARACHAIN_INHERENT_DATA_DISPUTE_SETS_INCLUDED, PARACHAIN_INHERENT_DATA_DISPUTE_SETS_PROCESSED,
PARACHAIN_INHERENT_DATA_WEIGHT,
};
use elexeum_runtime_metrics::{Counter, CounterVec};
pub struct Metrics {
/// Samples inherent data weight.
inherent_data_weight: CounterVec,
/// Counts how many inherent bitfields proce... | Rust | 0 |
PreOrder>,
_bots: PMutPtr<[T]>,
}
///An owned dinotree componsed of `T:Aabb`
pub struct DinoTreeOwned<A: Axis, T: Aabb> {
tree: DinoTreeOwn<A, T>,
bots: Vec<T>,
}
impl<T: Aabb> DinoTreeOwned<DefaultA, T> {
pub fn new(bots: Vec<T>) -> DinoTreeOwned<DefaultA, T> {
Self::with_axis(default_axis(),... | Rust | 0 |
r cmd in ["sdist", "clean", "--help", "--help-commands", "--version"]:
if cmd in sys.argv:
setup_requires = []
break
else:
setup_requires = ["Cython>=0.19", "numpy>=1.6.1"]
with open("requirements.txt") as f:
requires = f.read().splitlines()
requires = [r.split()[0] for r in requires]
... | Python | 1 |
rustc-cfg=has_const_index");
println!("cargo:rustc-cfg=has_i128");
println!("cargo:rustc-cfg=has_ops_bound");
println!("cargo:rustc-cfg=has_pointer_methods");
println!("cargo:rustc-cfg=has_range_inclusive");
}
// TARGET
// ------
// We need to optimize limb size for per... | Rust | 0 |
PEQ_18_10, PEQ_18_9, PEQ_18_8, PEQ_18_7, PEQ_18_6, PEQ_18_5, PEQ_18_4, PEQ_18_3,
PEQ_18_2, PEQ_18_1,
],
xover: Some(Crossover {
peqs: &[BPF_18_1, BPF_18_5],
}),
compressor: Some(Compressor {
bypass: COMP_18_0_STATUS,
... | Rust | 0 |
derefenceble in rust
println!("address : {:p} {:p} , values : {:?}",box_point,adress,*box_point);
//I see some abstraction in Rust in the above line , without {:p} , rust
//automatically derefrenced the pointer hence :p must for pointer
println!("OK now observer carefully");
println!("Address of ad... | Rust | 0 |
required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.
use... | Rust | 0 |
l_scaled, y)
# 保存标准化参数和校准信息
calibration_info = {
'feature_names': ['LM', 'LVC', 'WM', 'WVC', 'SR', 'TR', 'SPL', 'IE', 'BAYES'],
'num_features': X.shape[1],
'feature_stats': feature_stats,
'sigmoid_params': {
'a': float(sigmoid_a),
'b': float(sigmoid_b... | Python | 1 |
taFrame to disk.
The driver is inferred from the file extension; `.shp` and `.gpkg` are safe.
"""
out_dir = os.path.dirname(out_path)
if out_dir and not os.path.exists(out_dir):
os.makedirs(out_dir, exist_ok=True)
LOGGER.info("Writing %d features → %s", len(gdf), out_path)
gdf.to_file(... | Python | 1 |
from typing import Dict, Any
class TextSplitter:
async def document(self, text: str, model: str, metadata: Dict[str, Any]) -> Dict[str, Any]:
return {
'text': text,
'metadata': metadata
} | Python | 1 |
j in indices]
else:
out_corner_position = out_corner_position.view(bs, num_queries, 3)
out_prob = out_prob.view(bs,num_queries, 2)
indices = []
for sample_batch_idx in range(bs):
valid_id = torch.where(out_prob[sample_batch_idx][:,0] > self.val_th)... | Python | 1 |
)
# Gérer le changement de numéro d'étape
old_number = step.number
new_number = step_update.number
if old_number != new_number:
# Mettre à jour les numéros des autres étapes
for other_step in project.steps:
if other_step.id != step_id:
if old_number < new_nu... | Python | 1 |
printError("Aborted while installing host tool.")
return exitCode()
printInfo("Target device is " + adb.targetDevice() + ".")
thread.start_new_thread(logcatThread, ())
thread.start_new_thread(inputThread, ())
try:
while True:
pass
except:
if exitC... | Python | 1 |
(self.device(), &gicr_typers, &state.rdist)?;
set_icc_regs(self.device(), &gicr_typers, &state.icc)?;
//Restore GICv3ITS registers
gicv3_its_attr_access(
self.its_device().unwrap(),
kvm_bindings::KVM_DEV_ARM_VGIC_GRP_ITS_REGS,
GITS_IIDR,
&state.i... | Rust | 0 |
t_item_childs(parent_item)
self.update_order_for_old_parent_node_childs(old_id_parent)
def update_order_for_parent_item_childs(self, parent_item, parent_node):
self.__osbm.obj_logg.debug_logger(
f"NodesEditorDialogWindow update_order_for_parent_item_childs(parent_item, parent_n... | Python | 1 |
import nltk
from nltk.sentiment import SentimentIntensityAnalyzer
from transformers import pipeline
# 初始化情感分析器
nltk.download('vader_lexicon')
sia = SentimentIntensityAnalyzer()
# 初始化情感分析模型
sentiment_pipeline = pipeline('sentiment-analysis')
async def initializeSentimentAnalysis():
"""
Initialize the sentimen... | Python | 1 |
ap for GetBalanceParams {}
impl IntoJsonMap for GetItemParams {}
<reponame>woodruffw-forks/json<gh_stars>1-10
// Adapted from https://github.com/Alexhuszagh/rust-lexical.
//! Compare the mantissa to the halfway representation of the float.
//!
//! Compares the actual significant digits of the mantissa to the
//! theor... | Rust | 0 |
ography::ALG_TYPE_BLOCK
| Cryptography::ALG_SID_AES_256,
/// Temporary algorithm identifier for handles of Diffie-Hellman–agreed keys.
AgreedkeyAny = Cryptography::ALG_CLASS_KEY_EXCHANGE
| Cryptography::ALG_TYPE_DH
| Cryptography::ALG_SID_AGREED_KEY_ANY,
/// An algorithm to create a ... | Rust | 0 |
Primitive::Mesh2D {
buffers: Mesh2D {
vertices: vec![
Vertex2D {
position: [0.0, height / 2.0],
color,
... | Rust | 0 |
from PyQt5.QtWidgets import QWidget, QLabel, QVBoxLayout
from PyQt5.QtGui import QPainter
from gui.widgets.colors import Colors
from gui.widgets.Settings import (SettingsDropdown, SettingsSlider, SettingsBoolean, ScrollableSettingsWidget,
)
class AimbotWidget(QWidget):
def __init... | Python | 1 |
import numpy as np
import pandas as pd
import json
import os
MISSING_VALUE = -1
# fix PATH
img_dir = 'your_path/deepfashion/fashion_resize'
annotations_file = os.path.join(img_dir, 'fashion-resize-annotation-train.csv') #pose annotation path
save_path = os.path.join(img_dir, 'trainK')
if not os.path.exists(save_path... | Python | 1 |
:
name = name[6:] # skip "model/"
assert name[-2:] == ":0"
name = name[:-2]
name = name.split('/')
pointer = model
for m_name in name:
if re.fullmatch(r'[A-Za-z]+\d+', m_name):
l = re.split(r'(\d+)', m_name)
else:
l... | Python | 1 |
"""Preprocessing"""
import numpy as np
# ============================================================
# ============================================================
def pca(x, num_comp=None, params=None, zerotolerance=1e-7):
"""Apply PCA whitening to data.
Args:
x: data. 2D ndarray [num_comp, num_dat... | Python | 1 |
import os
import subprocess
# Set some default environment provided at setup
try:
# noinspection PyUnresolvedReferences
from .envs import persistent_envs
for key, value in persistent_envs.items():
if key not in os.environ:
os.environ[key] = value
except ImportError:
pass
# Configs
... | Python | 1 |
# argparse.ArgumentParser para argumentos mais complexos
# Tutorial Oficial:
# https://docs.python.org/pt-br/3/howto/argparse.html
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument(
'-b', '--basic',
help='Mostra "Olá mundo" na tela',
# type=str, # Tipo do argumento
meta... | Python | 1 |
, Len::Len(2));
let k = raw.unsigned_integer().unwrap();
let v = raw.text().unwrap();
assert_eq!(0, k);
assert_eq!("text", &v);
let k = raw.unsigned_integer().unwrap();
let v = raw.unsigned_integer().unwrap();
assert_eq!(1, k);
assert_eq!(42, v);
}
... | Rust | 0 |
#[doc = "Writer for register INTENSET"]
pub type W = crate::W<u32, super::INTENSET>;
#[doc = "Register INTENSET `reset()`'s with value 0"]
impl crate::ResetValue for super::INTENSET {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Master Pending interrupt Ena... | Rust | 0 |
tition for resources in the China
/// (Beijing) region is "aws-cn".
pub partition: &'a str,
/// The service namespace that identifies the AWS product (for example, Amazon S3, IAM, or Amazon RDS). For a list of
/// namespaces, see
/// <http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namesp... | Rust | 0 |
_file_exits(
&vec![
"language/exception/catch_no_block.lay",
"language/exception/try_no_block.lay",
"language/exception/try_no_catch.lay",
],
ExecuteResult::CompileError,
)?;
test_file_with_stdio(
"language/exception/top_level_thrown.lay",
None,
Some(vec![
"IndexErro... | Rust | 0 |
1) -> List[str]:
if len(self.labels) <= self.chunk_size:
tops = self._rank(image_features, self.embeds, top_count=top_count)
return [self.labels[i] for i in tops]
num_chunks = int(math.ceil(len(self.labels) / self.chunk_size))
keep_per_chunk = int(self.chunk_size / num_... | Python | 1 |
XML objects.
pub fn xml_allocator<'gc>(
class: Object<'gc>,
proto: Object<'gc>,
activation: &mut Activation<'_, 'gc, '_>,
) -> Result<Object<'gc>, Error> {
let base = ScriptObjectData::base_new(Some(proto), Some(class));
Ok(XmlObject(GcCell::allocate(
activation.context.gc_context,
... | Rust | 0 |
or_path,
weights_name=_add_variant(SAFETENSORS_WEIGHTS_NAME, variant),
cache_dir=cache_dir,
force_download=force_download,
proxies=proxies,
local_files_only=local_files_only,
token=token,
... | Python | 1 |
ntext<'gc, '_>,
proto: Option<Object<'gc>>,
) -> Self {
ColorTransformObject(GcCell::allocate(
gc_context,
ColorTransformData {
base: ScriptObject::object(gc_context, proto),
params: ColorTransformParams {
red_multiplier: 0.... | Rust | 0 |
.into_iter()
.flat_map(|o| TupleTree(o).flatten())
.collect();
#[cfg(debug_assertions)]
for o in &cs.outputs {
assert!(tuple_free(o.clone()));
}
}
<filename>contracts/tests/psp22_flashmint.rs
// Copyright (c) 2012-2022 Supercolony
//
// Permission is hereby granted, free of ch... | Rust | 0 |
from typing import List, Optional
from marie.core.bridge.pydantic import Field
from marie.core.postprocessor.types import BaseNodePostprocessor
from marie.core.schema import MetadataMode, NodeWithScore, QueryBundle
class MetadataReplacementPostProcessor(BaseNodePostprocessor):
target_metadata_key: str = Field(
... | Python | 1 |
ive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct SudokuGrid {
block_width: usize,
block_height: usize,
#[serde(skip_serializing)]
size: usize,
cells: Vec<Option<usize>>
}
fn build_sudoku_grid<E: de::Error>(block_width: usize, block_height: usize,
cells: Vec<Option<usize>>) -> Result<... | Rust | 0 |
"""Utility to require DEFAULT_PIPELINE.args to be set before running scripts.
Usage:
from scripts.check_pipeline_init import require_pipeline_args
require_pipeline_args()
This raises RuntimeError with guidance if not set.
"""
from src.pipeline import DEFAULT_PIPELINE
def require_pipeline_args():
if DEFA... | Python | 1 |
import os, json, time
# Import local score file
import score
# Read JSON data from the given filepath
def read_json_data(filepath):
try:
with open(filepath, newline = '') as in_file:
return json.load(in_file)
except FileNotFoundError:
print("The '{}' file is missing!".format(filepat... | Python | 1 |
loaded
// xmlrpc: TODO
// xmlwriter: already loaded
// xsl: TODO
"zip" => BuiltinData {
packages: Some(vec![String::from("libzip-dev")]),
..BuiltinData::default()
},
};
}
/// Finds a builtin extensoin's data from either the internal registry or the ... | Rust | 0 |
"ids": {
"slug": "warcraft-2016"
}
}),
);
assert_eq!(
c,
Checkin {
client: &client,
body,
sharing: CheckinSharing {
twitter: true,
... | Rust | 0 |
#\!/usr/bin/env python3
"""简单测试转换流程"""
import json
from pathlib import Path
# 创建测试配置
def test_conversion_setup():
print("测试转换设置...")
# 1. 加载源配置
with open('/root/kimi-k2-instruct/config.json', 'r') as f:
config = json.load(f)
print(f"源模型: {config['num_hidden_layers']} 层, {config['n_rou... | Python | 1 |
from GangaCore.testlib.GangaUnitTest import GangaUnitTest
class TestSJIDName(GangaUnitTest):
"""test for sjid in filename names explain each test"""
def setUp(self):
"""Make sure that the Job object isn't destroyed between tests"""
extra_opts = [('TestingFramework', 'AutoCleanup', 'False'), ... | Python | 1 |
): Added to stddev to prevent dividing by zero
Returns:
torch.Tensor: Normalized tensor
"""
return normalize(data, mean, std, eps), mean, std
def normalize_complex(data, eps=0.):
"""
Normalize the given complex tensor using:
(data - mean) / (stddev + eps)
... | Python | 1 |
, column: usize| self.cells.get(row, column).is_alive() as usize;
let column_last = self.cells.column_count() - 1;
for row in 0..self.cells.row_count() {
let row_above = if row == 0 { self.cells.row_count() - 1 } else { row - 1 };
let row_below = if row == self.cells.row_count() ... | Rust | 0 |
from __future__ import annotations
from dataclasses import dataclass, asdict
from pathlib import Path
import json
CONFIG_DIR = Path.home() / ".crazygui"
CONFIG_PATH = CONFIG_DIR / "config.json"
@dataclass(frozen=True)
class Rates:
UDP_HZ: int = 100 # UDP 接收節拍
SETPOINT_HZ: int = 100 # RPYT 發送節拍
... | Python | 1 |
#!/usr/bin/env python
# Capstone Python bindings, by Nguyen Anh Quynnh <aquynh@gmail.com>
from __future__ import print_function
from capstone import *
from capstone.ppc import *
from xprint import to_hex, to_x_32
PPC_CODE = b"\x43\x20\x0c\x07\x41\x56\xff\x17\x80\x20\x00\x00\x80\x3f\x00\x00\x10\x43\x23\x0e\xd0\x44\x00... | Python | 1 |
nn, job_id, None).await.unwrap()
}
}
#[tokio::test]
async fn queue_create_delete() {
let (_ctx, mut conn) = init().await;
let queue_settings = queue::Settings::default();
assert_eq!(RedisManager::delete_queue(&mut conn, DEFAULT_QUEUE).await.unwrap(), false);
assert_eq!(RedisManager::create_or_upd... | Rust | 0 |
# coding: utf-8
"""
Airflow API
Airflow API. All endpoints located under ``/api/v2`` can be used safely, are stable and backward compatible. Endpoints located under ``/ui`` are dedicated to the UI and are subject to breaking change depending on the need of the frontend. Users should not rely on those but use ... | Python | 1 |
assert_eq!(
pending_block_iteration + 1,
tester.state_keeper.pending_block.pending_block_iteration
);
}
/// Checks if executing a proposed_block is done correctly
/// There are more chunks than one can fit in 1 block,
/// so 1 block should get sealed in the process.
#[tokio::test]
async fn few_... | Rust | 0 |
pub mod pcr3;
#[doc = "Pin Control Register 4\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rus... | Rust | 0 |
Log(id=prop.id, action=Action.CREATE, type=Property, level=4),
]
mock_repository.get_change_log.return_value = change_logs
# Inject the mock repository into the function
create_main, _ = prepare_sync_data(mock_repository)
_, _, metadata_to_create = zip(*create_main)
for md in metadata_to_create:
asser... | Python | 1 |
ublish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROV... | Rust | 0 |
let b = Point::from([2., 3., 5.]);
let c = Point::from([3., 5., 8.]);
let d = Point::from([5., 8., 13.]);
let v1 = Vertex::builder(&mut shape).build_from_point(a)?;
let v2 = Vertex::builder(&mut shape).build_from_point(d)?;
// Regular edge
assert_eq!(
sup... | Rust | 0 |
RE: f64 = 0.1;
fn random_scene(rng: &mut impl rand::RngCore) -> HittableList {
let mut objects: Vec<Arc<dyn Hittable + Send + Sync>> = Vec::new();
let checker: Arc<dyn Texture + Send + Sync> = Arc::new(CheckerTexture::new(
Color::new(0.2, 0.3, 0.1),
Color::new(0.9, 0.9, 0.9),
));
let gr... | Rust | 0 |
ssert not vec.is_spacelike()
vec = vector.backends.object.VectorObject4D(
vector.backends.object.AzimuthalObjectRhoPhi(1, 0),
vector.backends.object.LongitudinalObjectEta(0),
vector.backends.object.TemporalObjectT(2),
)
assert not vec.is_spacelike()
def test_rhophi_eta_tau():
... | Python | 1 |
s_empty() {
return false;
}
vec![*g; gang.triggers.len()]
.iter()
.copied()
.enumerate()
.collect()
} else {
//dangling
return false;
}
} else {
//dangling
... | Rust | 0 |
cc prove that the argument is within bounds.',
'CONFIG_ARCH_HAS_DEBUG_STRICT_USER_COPY_CHECKS': 'Required to enable DEBUG_STRICT_USER_COPY_CHECKS, but alone does not provide security.',
'CONFIG_IKCONFIG_PROC': 'Enables access to the kernel config through /proc/config.gz. Leaking the kernel configuration would a... | Python | 1 |
r"}),
),
)
def test_deactivate_block(
decoy: Decoy,
mock_core: ThermocyclerCore,
mock_broker: LegacyBroker,
subject: ThermocyclerContext,
) -> None:
"""It should turn off the well block temperature controller via the core."""
subject.deactivate_block()
decoy.verify(
mo... | Python | 1 |
Codec;
impl Decoder for ByteCodec {
type Item = Vec<u8>;
type Error = io::Error;
fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Vec<u8>>, io::Error> {
let len = buf.len();
Ok(Some(buf.split_to(len).to_vec()))
}
}
impl Encoder for ByteCodec {
type Item = Vec<u8>;
typ... | Rust | 0 |
u8, // This doesn't do anything
u: u8, // Unused
v: u8, // Overflow
n: u8, // Negative
interrupt: u8,
// stall: u32
}
pub enum Interrupt {
IntNMI,
IntIRQ,
IntNone,
}
fn pages_differ(one: u16, two: u16) -> bool {
one & 0xFF00 != two & 0xFF00
}
impl CPU {
pub fn new(mem: ... | Rust | 0 |
#!/usr/bin/python
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hop... | Python | 1 |
username: &str) -> bool {
const ALLOWED_SPECIAL_CHARS: &str = ".-_ ";
if username.is_empty() {
return false;
}
username
.chars()
.all(|c| c.is_alphanumeric() || ALLOWED_SPECIAL_CHARS.contains(c))
}
pub fn serde_parse_f64_option<'de, D>(deserializer: D) -> Result<Option<f64>, D... | Rust | 0 |
import numpy as np
def select_waypoint(x, waypoints, curr_idx, threshold=0.3):
if curr_idx >= len(waypoints) or curr_idx==-1:
return waypoints[-1], curr_idx # Stay at last waypoint
distance = np.linalg.norm(waypoints[curr_idx] - x[:2])
if distance < threshold and curr_idx < len(waypoints) - 1:
... | Python | 1 |
umetricData | str]]:
"""Extract volumetric data from an arrow table.
Defaults to extracting all available data within an archive.
"""
all_file_names = table["file_name"].to_pylist()[0]
files = set(file_names or all_file_names).intersection(all_file_names)
output_data: l... | Python | 1 |
import json
from .oauth import OAuth2Test
class DigitalOceanOAuthTest(OAuth2Test):
backend_path = "social_core.backends.digitalocean.DigitalOceanOAuth"
user_data_url = "https://api.digitalocean.com/v2/account"
expected_username = "sammy@digitalocean.com"
access_token_body = json.dumps(
{
... | Python | 1 |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | Python | 1 |
ID,格式如:mssql-dj5i29c5n,与云数据库控制台页面中显示的实例 ID 相同,可使用 DescribeDBInstances 接口获取,其值为输出参数中字段 InstanceId 的值。
:type InstanceId: str
:param _Offset: 分页,页数,默认0
:type Offset: int
:param _Limit: 分页,页大小,默认20,最大不超过100
:type Limit: int
"""
self._InstanceId = None
self._O... | Python | 1 |
ers/{carol_id}",
headers={"Authorization": f"Bearer {token_admin}"},
)
assert res.json()["is_admin"] is False
res = await client.post(
f"/api/v1/users/{carol_id}/promote",
headers={"Authorization": f"Bearer {token}"},
)
assert res.status_code == 403
@pytest.mark.asyncio
as... | Python | 1 |
ype.StatisticsAlteration.html).
type StatisticsAlteration: Clone + Debug + Send;
#[cfg(feature = "serialization")]
/// See [StatisticsAlteration](type.StatisticsAlteration.html).
type StatisticsAlteration: Clone + Debug + Send + Serialize + for<'a> Deserialize<'a>;
/// See [Status](../status/type.S... | Rust | 0 |
class Solution:
def __init__(self):
self.BASE = 165_131
self.HASH = 8_417_508_174_513
def longestCommonSubpath(self, n: int, paths: list[list[int]]) -> int:
l = 0
r = len(paths[0])
while l < r:
m = l + (r - l + 1) // 2
if self._checkCommonSubpath(paths, m):
l = m
else... | Python | 1 |
nge>>;
/// Add a new lock to `Locks`
pub fn add_lock(locks: &mut Locks, lock_change: LockChange) {
locks
.entry(lock_change.composite_id().to_string())
.or_insert_with(HashSet::new)
.insert(lock_change);
tracing::debug!("(add) locks is now {:?}", locks);
}
/// Remove a lock from `Lock... | Rust | 0 |
or("random"));
let question = matches.value_of("question").unwrap_or("");
let result = iching::generate_reading(mode, question)?;
result.print();
Ok(())
}
<reponame>Lol3rrr/nolock
use std::{fmt::Debug, marker::PhantomData, mem::ManuallyDrop, sync::atomic};
use crate::hazard_ptr;
use super::{
entr... | Rust | 0 |
="Helvetica 12", bg="#f9ffff", fg="#000")
entry_btc.place(x=150, y=60)
tk.Button(
btc_frame,
text="Convert BTC → INR",
font="Helvetica 12 bold",
bg="#ffe6e6",
fg="#800000",
relief=tk.FLAT,
width=16,
command=convert_bitcoine
).place(x=150, y=100)
label_btc_result = tk.Label(btc_fr... | Python | 1 |
True)
cosine_matrix = torch.matmul(norm_context_hidden, norm_next_hidden.transpose(1, 2)).squeeze(-1) # [B*K, S]
degeneration_penalty, _ = torch.max(cosine_matrix, dim=-1) # [B*K]
next_top_k_probs = next_top_k_probs.view(-1) # [B*K]
contrastive_score = (1.0 - alpha) * next_top_k_probs - alpha * degen... | Python | 1 |
import sys
from collections import Counter
import tensorflow.contrib.keras as kr
if sys.version_info[0] > 2:
is_py3 = True
else:
reload(sys)
sys.setdefaultencoding("utf-8")
is_py3 = False
def native_word(word, encoding='utf-8'):
"""如果在python2下面使用python3训练的模型,可考虑调用此函数转化一下字符编码"""
if not is_py3... | Python | 1 |
import pygame
from pygame.locals import *
# Paramètres de la fenêtre et de la route
size = width, height = (800, 800)
road_w = int(width / 1.6)
roadmark_w = int(width / 80)
# Paramètres de l'animation
speed = 1
# Initialisation de Pygame
pygame.init()
running = True
# Création de la fenêtre
screen = pygame.display.... | Python | 1 |
d a Start/Stop Error. A Start or Stop was detected at a time when it is not allowed by the I2C specification. The Master interface has stopped driving the bus and gone to an idle state, no action is required. A request for a Start could be made, or software could attempt to insure that the bus has not stalled."]
ST... | Rust | 0 |
from flet.core.canvas.arc import Arc
from flet.core.canvas.canvas import Canvas, CanvasResizeEvent
from flet.core.canvas.circle import Circle
from flet.core.canvas.color import Color
from flet.core.canvas.fill import Fill
from flet.core.canvas.line import Line
from flet.core.canvas.oval import Oval
from flet.core.canva... | Python | 1 |
483647 | | | | | |",
"+---------------+--------------+------------+------------------+------------------+----------------+-------------+-----------------------------+--------------------------+------------------... | Rust | 0 |
# 2475. Number of Unequal Triplets in Array
# You are given a 0-indexed array of positive integers nums. Find the number of triplets (i, j, k) that meet the following conditions:
# 0 <= i < j < k < nums.length
# nums[i], nums[j], and nums[k] are pairwise distinct.
# In other words, nums[i] != nums[j], nums[i] != nums... | Python | 1 |
))
# Create the pipeline using the trained modules and save it.
accelerator.wait_for_everyone()
if accelerator.is_main_process:
unet = accelerator.unwrap_model(unet)
if args.use_ema:
ema_unet.copy_to(unet.parameters())
pipeline = AutoPipelineForText2Image.from_pretraine... | Python | 1 |
src_data: *const libc::c_void,
mut p_dest_data: *mut libc::c_void,
mut p_nb_elem: OPJ_UINT32,
) {
let mut l_src_data = p_src_data as *mut OPJ_BYTE;
let mut l_dest_data = p_dest_data as *mut OPJ_FLOAT32;
let mut i: OPJ_UINT32 = 0;
let mut l_temp: OPJ_UINT32 = 0;
i = 0 as libc::c_int as OPJ_UINT32;
while ... | Rust | 0 |
Use 32-bit atomic instead of 64-bit; latter may not be available on
32-bit platforms (powerpc, earmv7).
--- src/tools/rls/rls/src/cmd.rs.orig 2019-04-10 18:46:16.000000000 +0000
+++ src/tools/rls/rls/src/cmd.rs
@@ -17,7 +17,7 @@ use crate::config::Config;
use crate::server::{self, LsService, Notification, Request, R... | Rust | 0 |
}
RlispErrorKind::ImproperList => {
write!(f, "found an improper list where a proper one was expected")
}
RlispErrorKind::UnboundSymbol { sym } => write!(f, "symbol {} is unbound", sym),
RlispErrorKind::RustError(ref e) => write!(f, "INTERNAL:... | Rust | 0 |
92_SHA384,
RSA_PSS_2048_8192_SHA512,
}
fn parse_public_key(input: untrusted::Input)
-> Result<(untrusted::Input, untrusted::Input),
error::Unspecified> {
input.read_all(error::Unspecified, |input| {
der::nested(input, der::Tag::Sequence, error::Unspecif... | Rust | 0 |
ALETTE
WSB_PROP_MASK
FSB_FLAT_MODEFSB_ENCARTA_MODEFSB_REGULAR_MODEr r r r r <module>r *
"*CK 3;CK 3;CK 3;CK 3;CK 3;CK 3;CK 3;CK 3;CK 3;CK 3;
S[
CK CK 3;CK ... | Python | 1 |
inspace(0, partition_len, num=partition_len // fstp)
indices = np.concatenate((indices, np.ones(fpc - partition_len // fstp) * partition_len,))
indices = np.clip(indices, 0, partition_len-1).astype(np.int64)
# --
indices = indices + i * par... | Python | 1 |
Segment::SS => write!(f, "ss"),
}
}
}
impl fmt::Display for RegSpec {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let name = match self.bank {
RegisterBank::Q => {
["rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "... | Rust | 0 |
protocol_version(ProtocolVersion::Bft)
.build();
setup.wait_server_online();
let mock_result = mock_controller.finish_and_verify_that(|mock_verifier| {
mock_verifier.method_executed_at_least_once(MethodType::Handshake)
});
setup.server.shutdown();
assert_eq!(
mock_result,
... | Rust | 0 |
f not success:
print("水印嵌入失败")
return
# 2. 提取水印
print("\n2. 提取水印...")
extracted_watermark = "extracted_watermark.png"
success = watermark_system.extract_watermark(watermarked_image, input_image, extracted_watermark)
if not success:
print("水印提取失败")
return
... | Python | 1 |
{
let mut output = Self::new();
output.extend(iterable);
output
}
}
}
impl<A> Extend<char> for Tendril<fmt::UTF8, A>
where A: Atomicity,
{
#[inline]
fn extend<I>(&mut self, iterable: I)
where I: IntoIterator<Item = char>,
{
let iterator = ... | Rust | 0 |
input_xi_get_property_items_sizeof)(_buffer, num_items, format)
}
/// Returns `true` iff the symbol `xcb_input_xi_get_property_items_sizeof` could be loaded.
#[cfg(feature = "has_symbol")]
pub fn has_xcb_input_xi_get_property_items_sizeof(&self) -> bool {
has_sym!(self, xcb_input_xi_get_propert... | Rust | 0 |
mid3478);
let output0 = AvxVector::add(output0_left, output0_right);
output.store_partial1_complex(output0, 0);
// we need to add the first input to each of our 5 twiddles values -- but right now, input0 is duplicated into both slots
// but we only want to add it once, so zero the seco... | Rust | 0 |
), None),
(active, rtm_target_feature, "1.35.0", Some(44839), None),
(active, f16c_target_feature, "1.36.0", Some(44839), None),
(active, riscv_target_feature, "1.45.0", Some(44839), None),
// -------------------------------------------------------------------------
// feature-group-end: actual fea... | Rust | 0 |
ut.trim().parse() {
Ok(n) => n,
Err(e) => std::panic::panic_any(Beam::trouble(&format!(
"(Err.38) Failed to parse. / {}",
e
))),
}
};
let tokens: Vec<&str> = input.split(' ').collect();
// Beam::... | Rust | 0 |
else:
masklist = cache[server, channel] = MaskList(server, channel)
if mask in masklist:
masklist[mask].deserialize(infolist['value'])
else:
obj = masklist[mask] = MaskObject(mask)
obj.deserialize(infolist['value'])
weechat.config_uns... | Python | 1 |
f"Configuration request failed: {config_response.status_code}")
except Exception as e:
self.log_test("Auto-Wipe Configuration", False, f"Exception: {str(e)}")
def run_all_security_tests(self):
"""Run all security verification tests"""
print("🔒 COMPREHENSIVE... | Python | 1 |
),
# Real-world examples
(
'find . -name "*.txt" -exec grep "${PATTERN:-default}" {} \\;',
'find . -name "*.txt" -exec grep "${PATTERN:-default}" {} \\\\;',
),
(
'echo "Current path: ${PWD}/$(basename `pwd`)" \\| grep home',
'echo "Curren... | Python | 1 |
# This is the famous game ping pong
from turtle import Screen,Turtle
from ball import Ball
from paddle import Paddle
import time
from score_board import Scoreboard
screen = Screen()
screen.title("Pong")
screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.tracer(0)
pladdle_player1 = Paddle(side="left")... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.