text string | label_name string | labels int64 |
|---|---|---|
0,
value_absolute: x.abs() as UWord,
label: None,
},
Operand::Register(r) => OperandData {
addressing_mode: 1,
register_number: *r,
value_is_positive: true,
value_absolute: 0,
label: ... | Rust | 0 |
import cv2
import numpy as np
# Create the screen size
screen_res = (3840, 2160) # Adjust this to your screen resolution
# Define colors (white, red, green, blue)
colors = [
np.full((screen_res[1], screen_res[0], 3), fill_value=(255, 255, 255), dtype=np.uint8), # White
np.full((screen_res[1], screen_res[0],... | Python | 1 |
function(node)
{
return {
aD: {
X: node.scrollWidth,
N: node.scrollHeight
},
aK: {
_: node.scrollLeft,
aa: node.scrollTop,
X: node.clientWidth,
N: node.clientHeight
}
};
});
}
var _Browser_setViewportOf = F3(function(id, x, y)
{
return _Browser_withNode(id, function(node)
{... | Rust | 0 |
bpf_attach_type_BPF_SK_SKB_STREAM_VERDICT,
0,
)
};
if ret < 0 {
Err(Error::BPF)
} else {
Ok(())
}
}
}
impl<'a> SockMap<'a> {
pub fn new(map: &'a Map) -> Result<SockMap<'a>> {
Ok(SockMap { base: map })
}
... | Rust | 0 |
d, date_str, pageview_str
def reducer2(min_days, args):
'''
For each article, emit a row containing dates, pagecounts, total_pageviews
Only emit if number of records >= min_days
Also emit user rating sum and count for use in Hive Join:
line = 'Barack_Obama\t[20090419,20090420,' +
'20090421,20090422]\t[14... | Python | 1 |
import argparse
import os
import glob
import cv2
import shutil
import json
from sahi.slicing import slice_coco
from sahi.utils.coco import Coco
def main(args):
shutil.rmtree(os.path.join(args.coco_annotation_dir, "yolo"), ignore_errors=True)
shutil.rmtree(os.path.join(args.coco_annotation_dir, "sliced"), ignore_... | Python | 1 |
r"""Propigates the features of one set to another
Parameters
----------
mlp : list
Pointnet module parameters
bn : bool
Use batchnorm
"""
def __init__(self, mlp, bn=True):
# type: (PointnetFPModule, List[int], bool) -> None
super(PointnetFPModule, self).__init_... | Python | 1 |
# -*- coding: utf-8 -*-
# Scrapy settings for kuan2 project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/... | Python | 1 |
,
GIB..TIB => write!(f, "{:.2} GiB", count / GIB as f32)?,
_ => write!(f, "{:.2} TiB", count / TIB as f32)?,
};
Ok(())
}
}
<reponame>r4ntix/influxdb_iox
//! Namespace within the whole database.
use crate::{
cache::CatalogCache, chunk::ChunkAdapter, ingester::IngesterCon... | Rust | 0 |
"public/taskgraph/not_a_diff.txt": "Not a diff",
}
}
}
)
mock_taskgraph_diff_comm_task.load_artifacts(queue)
# The summary.json is WARNING, but the task is not from gecko so no extra reviewer group is added
assert mock_taskgraph_diff_comm_task.artifact_url... | Python | 1 |
# modules/vector_store.py
from langchain.vectorstores import FAISS
from langchain.embeddings import HuggingFaceEmbeddings
from typing import List, Dict
import os
class VectorStore:
def __init__(self, config):
self.config = config
# model_path = config.EMBEDDING_MODEL
model_path = os.path.j... | Python | 1 |
ndex: T::AccountIndex) -> Option<T::AccountId> {
let enum_set_size = Self::enum_set_size();
let set = Self::enum_set(index / enum_set_size);
let i: usize = (index % enum_set_size).as_();
set.get(i).cloned()
}
/// `true` if the account `index` is ready for reclaim.
pub fn can_reclaim(try_index: T::AccountInd... | Rust | 0 |
options are auto-generated.
// - All other options values default to an empty string.
// - All options are saved in the global hash before being returned for future
// use.
pub fn get_option(name: &str, options: &mut Options, args: &str) -> Result<String> {
let words: Vec<&str> = args.split_whitespace().collect(... | Rust | 0 |
xform)
for i in range(global_xform.shape[1]):
if i == 0:
local_xform[:, i] = global_xform[:, i]
else:
local_xform[:, i] = torch.bmm(torch.linalg.inv(global_xform[:, self.parents[i]]), global_xform[:, i])
return local_xform
def global_to_local... | Python | 1 |
y_fee = fees.trade_fee(dy)?;
let admin_fee = fees.admin_trade_fee(dy_fee)?;
let amount_swapped = dy.checked_sub(dy_fee)?;
let new_destination_amount = swap_destination_amount
.checked_sub(amount_swapped)?
.checked_sub(admin_fee)?;
let new_source_amount = swap_sou... | Rust | 0 |
ofile)
// Remove levels with missing data
.filter(|(_, p, h, t)| p.is_some() && h.is_some() && t.is_some())
// Unpack from `Optioned` type and discard the height, we no longer need it.
.map(|(i, p, _, t)| (i, p.unpack(), t.unpack()))
// Only look up to about 700 hPa
.take... | Rust | 0 |
"dUuid"]
pub event_id: Uuid,
#[sql_type = "Text"]
pub code_type: CodeTypes,
#[sql_type = "Array<Text>"]
pub redemption_codes: Vec<String>,
#[sql_type = "BigInt"]
pub max_uses: i64,
#[sql_type = "Nullable<BigInt>"]
pub discount_in_cents: Option<i64>,
#[sql_type = "Nullable<BigInt... | Rust | 0 |
#!/usr/bin/env python
# ========================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF l... | Python | 1 |
<T> ::std::ops::IndexMut<$name> for [<$name Array>]<T> {
fn index_mut(&mut self, x: $name) -> &mut Self::Output {
&mut self.data[x as ::std::primitive::usize]
}
}
impl<'a, T> ::std::iter::IntoIterator for &'a [<$name Array>]<T> {
... | Rust | 0 |
vl(func: CallbackPtr,
args: *const c_void,
unblock_func: CallbackPtr,
unblock_args: *const c_void)
-> *mut c_void;
// void *
// rb_thread_call_without_gvl2(voi... | Rust | 0 |
()? {
return Err(Error::CaskFileFull);
}
let mut buffer = &mut *APPEND_BUFFER.get().borrow_mut();
let writer = IoWrite::new(&mut buffer);
let mut ser = Serializer::new(writer).packed_format();
record.serialize(&mut ser).context(CborEncodeError)?;
let pos = sel... | Rust | 0 |
let expr = match ast::Expr::cast(expr_syntax) {
Some(e) => e,
None => unreachable!(),
};
// Note how expr is also a reference!
let expr: &ast::Expr = expr;
// This is possible because the underlying representation is the same:
assert_eq!(
expr as *const ast::Expr as *c... | Rust | 0 |
from .ablation.simple_net_without_channel_recombination import \
SimpleSleepNetEpochEncoderWithoutChannelRecombination
from .ablation.simple_net_without_frequency_reduction import \
SimpleSleepNetEpochEncoderWithoutFrequencyReduction
from .legacy.chambon_net import ChambonEpochEncoder
from .legacy.deep_sleep_ne... | Python | 1 |
the top left and bottom right
// corners are in space.
top_left: Point,
bottom_right: Point,
}
fn create_square(top_left: Point, height_width: f32) -> Rectangle {
let bottom_right = Point { x: top_left.x + height_width, y: top_left.y - height_width };
Rectangle {
// struct instantiati... | Rust | 0 |
rd GHn d | _ | j s| j r | r Pqq q| | j k r5| j j
| j d | _ | j rd | _ | j s(| j r | r Pq2q qq| j rY| | j k rY| | _ q| j r| | j k rd
} | | _ q| | j k s| | j k s| j r| j | | _ q| j j | | j d k rd GHn ... | Python | 1 |
"""Sub-module containing command generators for the velocity-based locomotion task."""
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.lab.managers import CommandTerm
if TYPE_CHECKING:
from omni.isaac.lab.envs import ManagerBasedEnv
from .commands_cfg_quad i... | Python | 1 |
pass
def set(
self, section: SectionLike, name: NameLike, value: Union[ValueLike, bool]
) -> None:
if self.writable is None:
raise NotImplementedError(self.set)
return self.writable.set(section, name, value)
def sections(self) -> Iterator[Section]:
seen = ... | Python | 1 |
from __future__ import annotations
from typing import Optional
import matplotlib.pyplot as plt
import networkx as nx
import torch
from torch_geometric.data import Data
from torch_geometric.utils import to_networkx
def plot_graph(
data: Data,
title: Optional[str] = None,
node_color: Optional[str] = None,... | Python | 1 |
pub all_funcs: *const RUSizePolicyAllFuncs,
}
<gh_stars>0
#![allow(proc_macro_derive_resolution_fallback)]
use diesel;
use diesel::prelude::*;
use crate::post::model::NewPost;
use crate::post::model::Post;
use crate::schema::posts;
use crate::schema::posts::dsl::*;
pub fn create_post(new_post: NewPost, conn: &PgCon... | Rust | 0 |
"""
Data utilities for DeepSpeed QLoRA training.
"""
import json
import os
import logging
from typing import Dict, List, Optional, Union
import numpy as np
from datasets import Dataset, DatasetDict
import torch
import transformers
logger = logging.getLogger(__name__)
def preprocess(
source,
tokenizer: transf... | Python | 1 |
\\p qureg = \\f$ \\rho \\f$ is a density matrix."]
#[doc = ""]
#[doc = " \\p allPauliCodes is an array of length \\p numSumTerms*\\p qureg.numQubitsRepresented"]
#[doc = " which specifies which Pauli operators to apply, where 0 = \\p PAULI_I, 1 = \\p PAULI_X,"]
#[doc = " 2 = \\p PAULI_Y, 3 = \\p PAULI_... | Rust | 0 |
].nrows()
nrows_msg = 'Input tensors have incompatible shapes.'
nrows_checks = [
check_ops.assert_equal(rt.nrows(), rt_nrows, message=nrows_msg)
for rt in rt_inputs[1:]
]
with ops.control_dependencies(nrows_checks):
# Concatentate the inputs together to put them in a single ragged tensor.
c... | Python | 1 |
})
results.sort(key=lambda x:x['score'],reverse=True)
if len(results)>show_search_limit:
results=results[:show_search_limit]
end_time=time.time()
ygo_sql=sqlite3.connect(c_ygo_dir)
for card in results:
try:
cursor = ygo_sq... | Python | 1 |
from fastapi import Request, Response,HTTPException
from dotenv import load_dotenv
from fastapi import Security
from fastapi.responses import JSONResponse
from datetime import timedelta,datetime,timezone
from typing import Optional
from jose import jwt,JWTError
import os
from src.shared.utils.response.response_factor... | Python | 1 |
# Copyright (c) 2023, NVIDIA CORPORATION.
# 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 i... | Python | 1 |
$ S SK Jr / SQrS rS rg) _sub_module_deprecationkaiser_betakaiser_atten kaiserordfirwinfirwin2remezfirls
minimum_phasec [ $ )N__all__ !scipy\signal\fir_filter_design.py__dir__r
Nr c ... | Python | 1 |
plt.plot(range(1, len(population_sizes) + 1), population_sizes, label="Population Size", color="blue", linewidth=2)
# Plot Average Fitness
plt.plot(range(1, len(average_fitness) + 1), average_fitness, label="Average Fitness", color="green", linewidth=2)
# Plot Trait Averages
for trait, averages i... | Python | 1 |
nce
/// of a node-induced subgraph of first isomorphic to second graph.
/// Default: ``True``.
/// :param int call_limit: An optional bound on the number of states that VF2 algorithm
/// visits while searching for a solution. If it exceeds this limit, the algorithm
/// will stop. Default: ``None``.
///
... | Rust | 0 |
import os
import json
import re
def safe_filename(title):
"""
Return a sanitized version of 'title' for filenames.
Removes non-ASCII characters (including emojis),
then replaces typical forbidden characters with '_'.
"""
# Remove all non-ASCII (including emojis)
title = re.sub(r'[^\x00-\x7F... | Python | 1 |
x.copy_from_slice(&bytes[1..33]);
y.copy_from_slice(&bytes[33..65]);
backend::Point::norm_from_coordinates(x, y).map(|p| Point::from_inner(p, Normal))
}
/// Samples a point uniformly from the group.
///
/// # Examples
///
/// Generate a random point from `thread_rng`.
... | Rust | 0 |
;
pub const SDP_ATTRIB_HID_LANG_ID_BASE_LIST: u16 = 0x0207;
pub const SDP_ATTRIB_HID_SDP_DISABLE: u16 = 0x0208;
pub const SDP_ATTRIB_HID_BATTERY_POWER: u16 = 0x0209;
pub const SDP_ATTRIB_HID_REMOTE_WAKE: u16 = 0x020A;
pub const SDP_ATTRIB_HID_PROFILE_VERSION: u16 = 0x020B;
pub const SDP_ATTRIB_HID_SUPERVISION_TIMEOUT: ... | Rust | 0 |
93, 1.7001064,
1.7047157, 1.7093376, 1.7139723, 1.7186192, 1.7232789, 1.7279512, 1.7326363, 1.7373339,
1.7420442, 1.7467673, 1.7515033, 1.756252, 1.7610139, 1.7657884, 1.770576, 1.7753766, 1.78019,
1.7850167, 1.7898563, 1.794709, 1.7995751, 1.8044541, 1.8093464, 1.814252, 1.8191712, ... | Rust | 0 |
rker=dict(
colorscale='Blues',
line=dict(width=1, color='white')
),
hovertemplate='<b>%{label}</b><br>Percentage: %{value:.2f}%<extra></extra>'
), row=1, col=1)
# Add ranking table
ranking_data = [
[f"#{i+1} - {holder['address'][:3]}...{holder['address'][-3:]... | Python | 1 |
from flet import *
from ..animations.high_light import high_light
class MoreOptions(Container):
def __init__(self):
super().__init__()
self.visible = False
self.selected_priority = None
self.width = 250
self.left = 600
self.top = 170
self.bgcolor = "#272727"... | Python | 1 |
-> Option<String> {
if cfg!(target_os = "linux") {
return Some(String::from("/"));
} else if cfg!(target_os = "windows") {
return Some(String::from("C:\\"));
} else {
return None;
}
}
pub struct Config {
pub path: String,
pub regex_expr: String,
}
impl Config {
pub... | Rust | 0 |
ngs,
) {
let (_, _) = (object, input);
}
pub fn serialize_structure_scte27_destination_settings(
object: &mut smithy_json::serialize::JsonObjectWriter,
input: &crate::model::Scte27DestinationSettings,
) {
let (_, _) = (object, input);
}
pub fn serialize_structure_smpte_tt_destination_settings(
obj... | Rust | 0 |
g_index()
self._rebuild_rag_index()
def _rebuild_long_index(self):
with sqlite3.connect(self.db_path) as con:
rows = con.execute("SELECT id,embedding FROM long_term").fetchall()
if not rows:
self.long_index = None
self.long_id_map = []
return
... | Python | 1 |
[dic["image_id"]], ass_pred_by_image[dic["image_id"]],img.shape[:2])
# ins_predictions,ass_predictions = matchor(ins_predictions,ass_predictions)
if ins_predictions == None:
continue
vis = Visualizer(img, metadata)
# vis = Visualizer(img,metadata)
vis_assa = vis.draw... | Python | 1 |
def get_dummy_inputs(self, device, seed=0):
if str(device).startswith('mps'):
generator = torch.manual_seed(seed)
else:
generator = torch.Generator(device=device).manual_seed(seed)
input_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(
device)
inputs = {'prompt'... | Python | 1 |
002,
"LAUNCHTUBE_API_ERROR": 500003
}
# Default metadata template
DEFAULT_METADATA_TEMPLATE = {
"version": "1.0",
"platform": "launchtube",
"encryption": "AES-256-GCM",
"created_at": None, # Will be set automatically
"updated_at": None, # Will be set automatically
"tags": [],
"access... | Python | 1 |
.id.clear();
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for CMsgSteamDatagramRouterPingReply_AltAddress {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for CMsgSteamDat... | Rust | 0 |
l.message)
break
print("--- Optimization summary")
print(foundcases[bestcase])
'Only breakes of no candidate point was found'
if not breaked:
print(" Add point: {}".format(XC[0,:]))
print(" Point accuracy: ... | Python | 1 |
# Copyright (c) 2025, sammish and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class AlternativeBatch(Document):
pass
| Python | 1 |
(state: TravelState) -> float:
# Note: problem states are (loc, tickets) but relaxed problem states are just loc
state_relaxed = state.loc
return future_costs_relaxed[state_relaxed].cost
cost = heuristic(TravelState(loc=4, tickets=3)) # @inspect cost
text("Let's compare UCS and A*")
... | Python | 1 |
to_supports(winners.as_ref(), staked.as_ref())
.unwrap()
.evaluate()
};
let enhance = is_score_better(balanced_score, unbalanced_score, Perbill::zero());
println!(
"iter = {} // {:?} -> {:?} [{}]",
iterations,
unbalanced_score,
balanced_score,
enhance,
);
// The only... | Rust | 0 |
.first()
)
if not access:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Permissão insuficiente para atualizar status",
)
# Atualizar status
old_status = mercadoria.status
mercadoria.status = new_status
try:
db.commit(... | Python | 1 |
387194, 2: 0.467045731687165, 3: 0.159984123349381, 4: 0.0821431680681869, 5: 0.0505765646770100,
6: 0.0345781523420719, 7: 0.0253132820710503, 8: 0.0194459129233227, 9: 0.0154831166726115, 10: 0.0126733075238887}
>>> E(robSol.subs(k, 10).subs(c, 0.05))
2.91358846104106
>>> P(robSol.subs(k, 4).subs(c,... | Python | 1 |
_system_set(
SystemSet::new()
.with_run_criteria(CombatState::Battle)
.with_system(show_valid_attack)
.with_system(highlight_attack_hover)
.with_system(attack_click_handler)
.with_system(try_attack_tile)
.with_sy... | Rust | 0 |
ta.create_gate("R1CS constraint", |meta| {
/// let a = meta.query_advice(a, Rotation::cur());
/// let b = meta.query_advice(b, Rotation::cur());
/// let c = meta.query_advice(c, Rotation::cur());
/// let s = meta.query_selector(s);
///
/// // BUG: Should be a ... | Rust | 0 |
"""
This module contains a class CustomHTMLRenderer, which uses
mistletoe to generate HTML from markdown.
Extra features include:
- Linkifying raw URLs
- Managing LaTeX so that MathJax will be able to process it in the browser
- Syntax highlighting with Pygments
"""
import re
from mistletoe import Document, HTMLRende... | Python | 1 |
done = false;
for _ in 0..30 {
done = c1.gossip_peers().len() == num - 1
&& c2.gossip_peers().len() == num - 1
&& c3.gossip_peers().len() == num - 1;
if done {
break;
}
sleep(Duration::new(1, 0));
}
assert!(done);
let mut p = Packet::d... | Rust | 0 |
rc;
use std::cell::Cell;
use al::graph::{GraphDef, Result};
use al::id::NodeTag;
use al::ops::nn::linear::Linear;
use al::ops::shape::avg_pool::AvgPool;
use al::ops::nn::bias::Bias;
use al::ops::nn::conv::Conv;
use al::ops::activ::tanh::Tanh;
use al::ops::activ::spline::Spline;
use al::ops::activ::softmax::Softmax;
use... | Rust | 0 |
matched_dict (dict of str: str): Internal UniChem mapping of
external servers.
Returns:
dict of str: [str]: Resource mapping. Key is a resource name,
value is the list of internal identifiers.
"""
mapping = []
url = f"{url_prefix}/{inchikey}"
try:
r = hel... | Python | 1 |
from store import Store
POSSIBLE_ACTIONS = [
'search_by_name',
'search_by_hashtag',
'add_item',
'remove_item',
'checkout',
'exit'
]
ITEMS_FILE = "items.yml"
def read_input():
line = input('What would you like to do?')
args = line.split(' ')
return args[0], ' '.join(args[1:])
de... | Python | 1 |
class Solution:
# dp, O(n^2)
# def longestIdealString(self, s: str, k: int) -> int:
# def isLegal(a,b):
# return abs(ord(a)-ord(b)) <= k
# n = len(s)
# dp = [1] * n
# for i in range(1,n):
# maxPre = 0
# for j in range(i):
# ... | Python | 1 |
self.run_gte::<f32>(context),
&Opcode::F64Eq => self.run_eq::<f64>(context),
&Opcode::F64Ne => self.run_ne::<f64>(context),
&Opcode::F64Lt => self.run_lt::<f64>(context),
&Opcode::F64Gt => self.run_gt::<f64>(context),
&Opcode::F64Le => self.run_lte::<f64>(context),
&Opcode::F64Ge => self.run_gte::<f... | Rust | 0 |
data_dir.clone(),
_log_file_name: [data_dir.clone(), PathBuf::from("log.log")]
.iter()
.collect(),
_cache_file_name: [data_dir.clone(), PathBuf::from("cache.json")]
.iter()
.collect()... | Rust | 0 |
ne, decl_macro)]
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
use diesel::dsl::sql_query;
use diesel::prelude::*;
use rocket::fairing::AdHoc;
use rocket::request::Form;
... | Rust | 0 |
import requests
import time
from typing import Dict, List, Optional
import json
class CoinGeckoPriceFetcher:
def __init__(self):
self.base_url = "https://api.coingecko.com/api/v3"
# 常見幣種的 symbol 到 CoinGecko ID 對照表
self.symbol_to_id = {
'AVAX': 'avalanche-2',
... | Python | 1 |
for j in 0..(1 << log2_line) {
/* E and O*/
for k in 0..4 {
E[k] = src[j * 8 + k] as i64 + src[j * 8 + 7 - k] as i64;
O[k] = src[j * 8 + k] as i64 - src[j * 8 + 7 - k] as i64;
}
/* EE and EO */
EE[0] = E[0] + E[3];
EO[0] = E[0] - E[3];
... | Rust | 0 |
class MT19937:
def __init__(self, seed):
self._index = 0
self._MT = [0] * 624
self._MT[0] = seed & 0xffffffff
for i in range(1, 624):
self._MT[i] = ((0x6c078965 * (self._MT[i-1] ^ (self._MT[i-1] >> 30))) + i) & 0xffffffff
def uint32(self):
if self._index == 0... | Python | 1 |
value = tags::Bits64::<V>::from_array(bytes);
if !L::DO_DEFAULT_CHECK || native_value != Default::default() {
field.push_in(native_value, bump);
}
} else {
Err(ErrorKind::UnexpectedWireType)?;
}
Ok(())
}
}
impl<L> DeserFieldFromBytesIter<L... | Rust | 0 |
from django.urls import path , include
from django.contrib.auth import views as auth_views
from . import views
from .views import *
urlpatterns = [
# post views
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('', views.dashboard, name=... | Python | 1 |
import psycopg2
from aws_redshift_config import aws_configure
from web_scrap_app import scrapping_app
import configparser
from botocore.exceptions import ClientError
#scrapping_app = scrapping_app()
def execute():
scrapping_app()
# def conf():
try:
config = configparser.ConfigParser()
co... | Python | 1 |
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from pydantic_extra_types.color import Color
triggerType = Literal["pressed", "released", "longpress"]
class UiTrigger(BaseModel):
"""
UI trigger configuration.
"""
model_config = ConfigDict(title="UI button configuration"... | Python | 1 |
ifferent type.
"""
pytree_test_utils.assert_tree_with_leaves_of_type(jax_tree, jnp.ndarray)
pytree_test_utils.assert_tree_with_leaves_of_type(np_tree, np.ndarray)
with pytest.raises(
AssertionError,
match=f"The tree has at least one leaf that is not of type {jnp.ndarray}.",
):
... | Python | 1 |
;
#[derive(Copy, Clone, PartialEq)]
enum Cell {
Wire(u8, u32),
Intersection(u32, u32),
}
struct Field {
num_wires: u8,
contents: HashMap<Point, Cell>,
intersections: Vec<u32>,
}
impl Field {
fn new() -> Self {
Field { num_wires: 0, contents: HashMap::new(), intersections: vec![] }
... | Rust | 0 |
si_code=CLD_EXITED, si_pid=16135, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---"[..];
let result = parse_call(input);
assert_eq!(result, Ok((&b""[..], Call::Signalled("{si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=16135, si_uid=1000, si_status=0, si_utime=0, si_stime=0}".into())... | Rust | 0 |
from collections import defaultdict, deque
class Grafo:
def __init__(self, vertices):
self.V = vertices
self.grafo = defaultdict(lambda: defaultdict(int)) # Grafo com capacidades
def adiciona_aresta(self, u, v, capacidade=1):
self.grafo[u][v] = capacidade
def bfs(self, origem, de... | Python | 1 |
let mut a = Array::<i32, _>::zeros((ADD2DSZ, ADD2DSZ));
let b = Array::<i32, _>::zeros((ADD2DSZ, ADD2DSZ));
let bv = b.view();
bench.iter(|| {
a += &bv;
});
}
#[bench]
fn add_2d_zip(bench: &mut test::Bencher) {
let mut a = Array::<i32, _>::zeros((ADD2DSZ, ADD2DSZ));
let b = Array::<i32... | Rust | 0 |
WPM_PROVIDER_CONTEXT3__0,
pub providerContextId: u64,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
impl ::core::marker::Copy for FWPM_PROVIDER_CONTEXT3_ {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
impl ::core::clone::Clone for FWPM_PROVIDER_CONTEXT3_ {
fn ... | Rust | 0 |
break
await page.wait_for_timeout(1000)
else:
logger.warning('⚠️ Turnstile чекбокс не з\'явився за 20 секунд')
except Exception as e:
... | Python | 1 |
rboard(output_folder_val),
inputs=[output_folder],
outputs=None,
)
# --- 「データセットの前処理」タブ ---
with gr.Tab(locale_data["LNG_TAB_DATASET_PROCESSING"]):
gr.Markdown(locale_data["LNG_DATASET_PROCESSING_DESC"])
with gr.Column():
... | Python | 1 |
#!/usr/bin/env python3
"""
Configuration file for Auto Web Page Refresher
You can modify these default values to customize the behavior of the script.
"""
# Default configuration settings
CONFIG = {
# Default refresh interval in minutes
'default_refresh_interval': 5,
# Default URL (leave empty to alw... | Python | 1 |
u<A, P>>),
And(Box<Mu<A, P>>, Box<Mu<A, P>>),
Or(Box<Mu<A, P>>, Box<Mu<A, P>>),
Gfp(String, Box<Mu<A, P>>),
All(A, Box<Mu<A, P>>),
Lfp(String, Box<Mu<A, P>>),
Ex(A, Box<Mu<A, P>>),
Var(String),
}
impl Mu<char, u32> {
fn parse_var(buff: &mut Buff<char>) -> Option<char> {
let c = ... | Rust | 0 |
e_3'}
{'a': {'b': 'stable_0', 'c': 'stable_1'}, 'b': 'stable_3'}
# nested stable values with lists
>>> x = {'a': [{'b': 1, 'c': [2]}, {'b': 3, 'c': 4}], 'b': [{'b': 1}]}; stabilize_key_values(x, ['a', 'b','c']); x;
{'1': 'stable_0', '[2]': 'stable_1', '3': 'stable_2', '4': 'stable_3', '[{"b": "stable_... | Python | 1 |
])),
PciBar::from(LittleEndian::read_u32(&bytes[4..8])),
];
let primary_bus_num = bytes[8];
let secondary_bus_num = bytes[9];
let subordinate_bus_num = bytes[10];
let secondary_latency_timer = byt... | Rust | 0 |
)
cy = sy2 + (sin_a * cx1 + cos_a * cy1)
# Calculate the start_angle (angle1) and the sweep_angle (dangle)
# ------------------------
ux = (x1 - cx1) / rx
uy = (y1 - cy1) / ry
vx = (-x1 - cx1) / rx
vy = (-y1 - cy1) / ry
# Calculate the angle start
# ------------------------
n... | Python | 1 |
(Box::new(Node {
occupied: 0b1,
children: vec![
Child::Tree(
Some(Box::new(Node {
occupied: 0b11,
children: vec![
Child::KV("a", 1),
... | Rust | 0 |
from sympy.tensor.array import (ImmutableDenseNDimArray,
ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray)
from sympy.abc import x, y, z
def test_NDim_array_conv():
MD = MutableDenseNDimArray([x, y, z])
MS = MutableSparseNDimArray([x, y, z])
ID = ImmutableDenseNDimArray([x, ... | Python | 1 |
else {
println!("Signature verify NOK");
}
if true == secp.verify_commit_sum(vec![output1, output2], vec![input, excess]) {
println!("\n\"subset sum\" verify OK:\toutput1+output2 = input+excess");
} else {
println!("\n\"subset sum\" verify NOK:\toutput1+outp... | Rust | 0 |
already in the requested state (attached or detached), the command is
/// ignored and OK result code is returned. If the requested state cannot be
/// reached, an error result code is returned. The command can be aborted if a
/// character is sent to the DCE during the command execution. Any active PDP
/// context wil... | Rust | 0 |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
from flask_migrate import Migrate
from flask_bcrypt import Bcrypt
from flask_restful import Api
from flask_cors import CORS
from dotenv import load_dotenv
import os
load_dotenv()
naming_convention = {
"ix": "ix_%(colum... | Python | 1 |
f6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73637265656e20776f756c642062652069742e",
associated_data: "50515253c0c1c2c3c4c5c6c7",
key: "<KEY>",
nonce: "404142434445464748494a4b4c4d4e4f5051525354555657",
ciphertext: "<KEY>... | Rust | 0 |
# Ruta corregida para editar presupuestos
@budget_bp.route('/edit/<int:budget_id>', methods=['POST'])
@login_required
def edit_budget(budget_id):
budget = Budget.query.get_or_404(budget_id)
# Verificar que el presupuesto pertenece al usuario actual
if budget.user_id != current_user.id:
return ... | Python | 1 |
import unittest
from unittest.mock import MagicMock, create_autospec, patch
from encourage.llm import BatchInferenceRunner, Response, ResponseWrapper
from encourage.metrics import ContextPrecision
from tests.fake_responses import create_responses
class TestContextPrecision(unittest.TestCase):
def setUp(self) -> ... | Python | 1 |
of `) "string"` or `NAME "string"`.
fn enclosing_func_call(tokens: &[NestedToken], pos: Pos) -> Option<(usize, usize)> {
// blank end of line
// | |
// ( N A M E , _ " s t _ r i n g " _ ) _ _ $
// 0 1 1 1 1 2 3 3 3 3 3 3 3 3 3 3 4 4 ... | Rust | 0 |
path(None::<String>);
// Get the path to the metadata file.
let metafile = metadir.join(CLIENT_ID_METAFILE);
if metafile.exists() {
// Return the contents of the file which is the Client ID
read_file(&metafile)
} else {
// Generate a new, random UUID for the Client ID.
le... | Rust | 0 |
(())
}
#[tracing::instrument(skip(stream, sim_thread_pool))]
async fn accept_connection(
peer: SocketAddr,
stream: TcpStream,
sim_thread_pool: Arc<ThreadPool>,
tick: Duration,
) {
let addr = stream
.peer_addr()
.unwrap_or_else(panic_on_err!("connected streams should have a peer addr... | Rust | 0 |
/Documenttype")
}
}
impl CodeableConceptEx for DocumentType {
type Coding = Self;
fn from_parts(coding: Self::Coding, _text: Option<String>) -> Self {
coding
}
fn coding(&self) -> &Self::Coding {
&self
}
}
<gh_stars>0
// Copyright 2019 TiKV Project Authors. Licensed under Apac... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.