text string | label_name string | labels int64 |
|---|---|---|
non_terminal: String,
pub lifetime: String,
pub type_ref: String,
}
#[cfg(test)]
pub mod some_event_for_test {
use std::fmt::{Debug, Formatter};
use dddk_macro::Event;
#[derive(Event)]
pub struct AnEvent {}
impl Debug for AnEvent {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt:... | Rust | 0 |
######################################################
print "starting training and testing"
print("...")
# Run the training
final_result = ""
for i in range(n_epochs):
print "epoch %s out of %s" % (i, n_epochs)
for batch_n in range(num_batches):
sta = batch_n*batch_size
end = sta + batch_size... | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# 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... | Python | 1 |
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## You may use this file under the terms of the BSD license as follows:
##
## "Redistrib... | Python | 1 |
// by means of BEGIN or COMMIT AND CHAIN, or implicitly, by the first
// transactional statement, when autocommit=off.
const SERVER_STATUS_IN_TRANS = 1;
// Autocommit mode is set
const SERVER_STATUS_AUTOCOMMIT = 2;
// Multi query - next query exists.
const SERVE... | Rust | 0 |
# coding: utf-8
"""
CNB OPENAPI
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 1.0
Contact: cnb@tencent.com
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class m... | Python | 1 |
solid #333; border-radius: 8px; }
.test-item { margin: 10px 0; padding: 10px; background: #2a2a2a; border-radius: 4px; }
.log { background: #1a1a1a; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 12px; max-height: 200px; overflow-y: auto; }
</style>
</head>
<body>
<h1>🔧 主... | Python | 1 |
default_app_config = 'mathefragen.apps.tutoring.apps.TutoringConfig'
TUTOR_PING_TEXT = """
Hi %s,
<p>%s braucht dringend Hilfe und bittet dich um eine private Unterrichtseinheit.
Klicke auf den unten stehenden Button um die Anfrage dir anzusehen.</p>
"""
TUTOR_TIME_OFFER_TEXT = """
Hi %s,
<p>%s hat einen neuen Term... | Python | 1 |
<()> {
let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
let field = ctx.find_node_at_offset::<ast::RecordField>()?;
let strukt_name = strukt.name()?;
let field_name = field.name()?;
let field_ty = field.ty()?;
// Return early if we've found an existing fn
let mut fn_name = to_lower_... | Rust | 0 |
.wav')
else:
wav_files.append(sample['file'])
label_index = self.word_to_index[sample['label']]
labels[i - offset, label_index] = 1
return wav_files, labels
def get_unprocessed_data(self, how_many, model_settings, mode):
"""Retrieve sample data for the given partition, with no tran... | Python | 1 |
IBV_WR_SEND_WITH_IMM: Type = 3;
pub const IBV_WR_RDMA_READ: Type = 4;
pub const IBV_WR_ATOMIC_CMP_AND_SWP: Type = 5;
pub const IBV_WR_ATOMIC_FETCH_AND_ADD: Type = 6;
pub const IBV_WR_LOCAL_INV: Type = 7;
pub const IBV_WR_BIND_MW: Type = 8;
pub const IBV_WR_SEND_WITH_INV: Type = 9;
pub const... | Rust | 0 |
v_file_path = "./ipt_file/"+ model_name +"_Importance_Score_dataset_id_"+ str(dataset_id) + "_" + str(service_id)+"-"+dataset_order[service_id]+".csv"
df.to_csv(csv_file_path, index=False)
model.save_pretrained(output_dir)
# df_log = pd.DataFrame(trainer.state.log_history)
#df_log.to_csv(os.path.j... | Python | 1 |
if let Some(same_name_hidden_locals) = self.hidden_local.get_mut(&local_val) {
if let Some(deepest_same_name_hidden_local) = same_name_hidden_locals.pop() {
// もし同じローカル変数がなくなった場合はハッシュテーブルのエントリを削除
if same_name_hidden_locals.is_empty() {... | Rust | 0 |
::Div for Foo {
type Output = Self;
fn div(self, other: Self) -> Self {
Foo { bar: self.bar / other.bar }
}
}
let lua = Lua::new();
lua.context(|ctx| {
let globals = ctx.globals();
globals.set("foo_one", Foo { bar: 25.0 })?;
globals.set("foo_two"... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
# Parameters for the simulation
n_iterations = 1000 # Number of iterations (time steps)
true_prob_A = 0.5 # True preference for A (50%)
true_prob_B = 0.5 # True preference for B (50%)
sample_size_per_step = 50 # Number of samples per step
# Lists to store cum... | Python | 1 |
format!("{}", e));
}
}
}
<filename>robin_web/src/main.rs
///! # Robin-Web
///!
///! This module defines how the translator should interact with the web page
#[macro_use]
extern crate stdweb;
extern crate robin_core;
use std::borrow::BorrowMut;
use stdweb::web::event::ClickEvent;
use stdweb::web::{docu... | Rust | 0 |
from .task_agent import multi_thread_get_query_reject_supply,\
get_question_zh,\
get_reinforced_qkw,\
get_reinforced_questions,\
multi_specific_event_related_judge, \
get_reject_judgement | Python | 1 |
) -> std::string::String {
return format!("\x1B[32m{}\x1B[0m", s);
}
fn yellow(s: &str) -> std::string::String {
return format!("\x1B[33m{}\x1B[0m", s);
}
fn blue(s: &str) -> std::string::String {
return format!("\x1B[34m{}\x1B[0m", s);
}
fn magenta(s: &str) -> std::string::String {
return format!("\x1B... | Rust | 0 |
PinkCarpet, // 1.13 (id: 30186)| 1.16.2 (id: 27381)
PinkConcrete, // 1.13 (id: 5227)
PinkConcretePowder, // 1.13 (id: 6421)
PinkDye, // 1.13 (id: 31151)
PinkStainedGlass, // 1.13 (id: 16164)
PinkStainedGlassPane, // 1.13 (id: 24637, stack: 0)
PinkTerracotta, // 1.13 (id: 23727)
PinkTulip, //... | Rust | 0 |
MemoryOp>,
) -> Result<(), Box<dyn std::error::Error>> {
for op in write_ops {
assert!(op.local_ptr_len <= WORD_SIZE);
if op.local_ptr_len < WORD_SIZE {
// Write op is smaller than a single word, so we should read memory before rewriting it.
let mut word = ptrace::read(pid,... | Rust | 0 |
n new_manager(
geth: &GethInstance,
) -> (
TransactionManager<
Factory<middleware_factory::HttpProviderFactory>,
BlockSubscriber<middleware_factory::WsProviderFactory>,
usize,
>,
BlockSubscriberHandle<Arc<Provider<Ws>>>,
) {
let retry = 0;
let delay = std::time::Duration:... | Rust | 0 |
print(json.dumps(json.loads(response.content.decode("utf-8")), indent=4))
exit(1)
# (Re)start the pipeline
print("Starting pipeline...")
requests.post(f"{api_url}/v0/pipelines/{pipeline_name}/start").raise_for_status()
response = requests.get(f"{api_url}/v0/pipelines/{pipeline_n... | Python | 1 |
alue 3 for QMFBID=0 (9x7 filter) is more suspicious, */
/* since F.2 and F.3 would lead to 4 instead, so the current 3 might be */
/* needed to be bumped to 4, in case inconsistencies are found while */
/* decoding parts of irreversible coded images. */
/* See opj_dwt_decode_partial_53 and opj_dwt_decode_partia... | Rust | 0 |
from vocpub_genericode.cli.app import app
| Python | 1 |
]
impl crate::Resettable for I2C_PRD_DATA_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0x0f0f_0f0f
}
}
// This is derivative work of https://athemathmo.github.io/2016/06/24/using-gmm-in-rust.html
// See - https://github.com/AtheMathmo/AtheMathmo.github.io/issues/2 for proof of license
//
... | Rust | 0 |
import pytest
from dvc.utils.serialize import parse_py
@pytest.mark.parametrize(
"text,result",
[
("BOOL = True", {"BOOL": True}),
("INT = 5", {"INT": 5}),
("FLOAT = 0.001", {"FLOAT": 0.001}),
("STR = 'abc'", {"STR": "abc"}),
("DICT = {'a': 1, 'b': 2}", {"DICT": {"a": ... | Python | 1 |
d::sync::Arc;
use indicatif::ParallelProgressIterator;
use jwalk::WalkDir;
use rayon::prelude::*;
use structopt::StructOpt;
use tempdir::TempDir;
use ty::reason::{BReason, NReason, Reason};
use hackrs::{decl_parser::DeclParser, folded_decl_provider::FoldedDeclProvider};
use hackrs_test_utils::cache::{make_shallow_de... | Rust | 0 |
self.parent.unwrap()
}
}
impl<'a> Spanned for TsRestType<'a> {
fn span(&self) -> Span {
self.inner.span()
}
}
impl<'a> From<&TsRestType<'a>> for Node<'a> {
fn from(node: &TsRestType<'a>) -> Node<'a> {
let node = unsafe { mem::transmute::<&TsRestType<'a>, &'a TsRestType<'a>>(node) };
Node::TsRestTy... | Rust | 0 |
ns(line_segment_two);
intersections.extend(
new_intersections
.into_iter()
.filter(|point| Point::new(0, 0) != *point)
.map(|point| {
let additional_steps_one =
... | Rust | 0 |
total_b += i * score
total_label.canvas[:-3, 10:] = total_label.canvas[1:-2, 10:]
total_label.canvas[-3, 10:]["char"] = " "
await anim_text.tween(
duration=0.5, easing="out_bounce", pos=(15, 10)
... | Python | 1 |
.get_meta().encryption.is_some(), true);
assert_ne!(img.get_image_data(), clean_data);
img.decrypt_mut(String::from("1234567812345678"));
assert_eq!(img.get_meta().encryption.is_none(), true);
assert_eq!(img.get_image_data(), clean_data);
}
#[test]
#[cfg(feature = "gzip")]
... | Rust | 0 |
# -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# 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
# (... | Python | 1 |
c 'images/no-cover.svg' %}}';\"")
print(f" 📋 Adicionar: loading=\"lazy\" class=\"google-books-image\"")
print(f"\n💡 Padrão de correção completo:")
print(f" <img src=\"{{% url 'image_proxy' %}}?url={{ livro.capa_url|urlencode }}\"")
print(f" alt=\"{{ livro.titulo }}\"")
... | Python | 1 |
to_owned());
}
}
for resource in remove {
manager.goals.remove(&resource);
}
}
<filename>week0chap05/src/main.rs
use rt::{
hitable::{Hitable, HitableList, Sphere},
material::Lambertian,
ray::Ray,
vec3::Vec3,
};
fn color(r: &Ray, world: &dyn Hitable) -> Vec3 {
if let Som... | Rust | 0 |
= 0,
triggerY = -73420,
triggerRange = 500,
actorX = 29850,
actorZ = 1500,
actorY = -73420,
flags = 0x007E,
talkScenaIndex = 0x0000,
talkFunc... | Python | 1 |
tion
Your job is to:
- Answer the user's question using the provided video context
- Be conversational and helpful
- Reference specific details from the videos when relevant
- If the context doesn't fully answer the question, acknowledge what you ... | Python | 1 |
# 从候选列表中取出距离最近的节点
cand_dist, cand_idx = heapq.heappop(candidates)
# 获取结果列表中最远的距离 (负数)
farthest_result_neg_dist = results[0][0]
# 优化: 如果当前候选节点的距离比结果中最远的还要远,则停止搜索
if cand_dist > -farthest_result_neg_dist:
break
... | Python | 1 |
"""
Configuration for technical indicators and trading signals.
"""
def get_base_config():
"""
Get base configuration for technical indicators.
These serve as default values before state-specific adjustments.
"""
return {
'rsi': {
'window': 14,
'threshold_percentile'... | Python | 1 |
ter(|| laymine_op(16, 30, 99, 8, 15));
} // 11,522 ns/iter
benchmark_group!(lay_mine, bench_laymine, bench_laymine_op);
benchmark_main!(lay_mine);
<filename>src/main.rs
use chrono::{
prelude::*,
Duration,
};
use std::thread::sleep;
mod display;
use display::DisplayController;
mod tibber;
use tibber::get_pric... | Rust | 0 |
, Any], summary="更新通知设置")
async def update_notification_settings(
request: NotificationSettingsRequest,
container: FrontendServiceContainer = Depends(get_frontend_service_container),
context: FrontendContext = Depends(get_frontend_context)
):
"""
更新用户的通知设置
"""
try:
logger.info(f"Fron... | Python | 1 |
nd_bundle(spend_bundle, now, MAX_BLOCK_COST_CLVM)
now.seconds += 500
now.height += 1
change_count = SINGLETON_WALLET.update_state(PUZZLE_DB, removals)
assert change_count == 1
assert len(list(coin_store.all_unspent_coins())) == 2
#######
# farm a `p2_singleton`
pool_reward_puzzle_hash... | Python | 1 |
,neighborhoods[v,:]>-1]]) for v in range(voxels)])
neighborhood_dist_incorrect = np.array([np.sum(dist_incorrect[neighborhoods[v,neighborhoods[v,:]>-1]]) for v in range(voxels)])
acc[idx,:] = (neighborhood_dist_correct < neighborhood_dist_incorrect)*1.0 + (neighborhood_dist_correct == neighborhood_dis... | Python | 1 |
format!(
"{} - {}.",
"关键字".cyan().bold(),
format!("{:?}", kw).dark_gray()
)
}
pub fn sea_unknown_id() -> String {
"未知_未知_未知_未知".to_string()
}
pub fn sea_invalid_id(kw: &str) -> String {
format!("无效的索引ID, {:?}", kw)
}
pub fn sea_in... | Rust | 0 |
if self.length as i64 + x < 0 => return Err(err),
SeekFrom::End(x) => min(self.length as i64 + x, self.length as i64) as u64,
SeekFrom::Start(x) => min(x, self.length as u64),
};
Ok(self.pos)
}
}
<reponame>mith-mmk/wml2-on-rust
use bin_rs::io::*;
use crate::error::*;
use cr... | Rust | 0 |
assed_tests}/{total_tests} passed ({success_rate:.1f}%)")
if success_rate >= 80:
print("🟢 Overall Status: ROUTING FIXED! - v4 is working properly")
elif success_rate >= 60:
print("🟡 Overall Status: PARTIAL FIX - Some routing issues remain")
else:
print("🔴 Overall Status: ROUT... | Python | 1 |
}
None => {
set_key_value(&self.value, &JsValue::from_str(key), &JsValue::UNDEFINED);
}
}
}
pub fn set_u32(self: &Memory, key: &str, value: Option<u32>) {
match value {
Some(v) => {
set_key_value(&self.value, &JsVa... | Rust | 0 |
culation.name])
if calculation == ExcitingCalculation.groundstate:
tolerances = ground_state_tolerances
if calculation == ExcitingCalculation.gw:
tolerances = gw_tolerances
if calculation == ExcitingCalculation.hybrid:
print(hybrid_message)
tolerances = hybrid_tolerances
... | Python | 1 |
s.len(), 2);
if (matches[0] != (0, 1) && matches[1] != (1, 1))
&& (matches[0] != (1, 1) && matches[1] != (0, 1))
{
assert_eq!(true, false);
}
}
example_map.set_stream_len(200);
let scaled = example_map.scaled(400, Some((100, 150)));
assert_eq!(scaled.len(... | Rust | 0 |
nd()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('outputs/gdp_forecast_plot.png', dpi=300)
print("Forecast plot saved to 'outputs/gdp_forecast_plot.png'")
# Create a more comprehensive visualization with actual vs predicted values
# for the historical period
if best_model:
fitted_values = best_model.f... | Python | 1 |
from .abstract import AbstractFeatureGenerator
from .astype import AsTypeFeatureGenerator
from .auto_ml_pipeline import AutoMLInterpretablePipelineFeatureGenerator, AutoMLPipelineFeatureGenerator
from .binned import BinnedFeatureGenerator
from .bulk import BulkFeatureGenerator
from .category import CategoryFeatureGener... | Python | 1 |
renderer::VertexPosNormal;
use amethyst::renderer::pass::Clear;
use amethyst::renderer::pass::DrawShaded;
use geometry::*;
struct Game;
impl State for Game
{
fn on_start(&mut self, world: &mut World, assets: &mut AssetManager, pipeline: &mut Pipeline)
{
let clear_layer = Layer::new("main", vec![
... | Rust | 0 |
35), best_position(&Map::from_file("sample2.txt").find_asteroids()));
assert_eq!((Pos::new(6, 3), 41), best_position(&Map::from_file("sample3.txt").find_asteroids()));
assert_eq!((Pos::new(11, 13), 210), best_position(&Map::from_file("sample4.txt").find_asteroids()));
let map = Map::from_file("input.txt");... | Rust | 0 |
문에서 계산
total = 0
# merged/plain 본문
for k in ("merged_text","text","plain_text"):
v = rec.get(k)
if isinstance(v, str):
total = max(total, len(v))
# texts dict 합산(중복 허용 X, 가장 큰 값 사용)
texts = rec.get("texts")
if isinstance(texts, dict):
s = 0
for v in te... | Python | 1 |
import numpy as np
# ---------------------------------------------
# Matrix with a single row. Different ways to implement.
# 1.
a = np.array([[1, 2, 3]])
# print(a)
# 2
b = [1, 2, 3]
# print(np.array([b]))
# 3
c = [1, 2, 3]
# print(np.expand_dims(np.array(c), axis=0))
# --------------------------------------------... | Python | 1 |
_('site name'),
max_length=200,
null=False,
blank=False,
default='')
site_description = models.TextField(
_('site description'),
max_length=1000,
null=False,
blank=False,
default='')
site_seo_description = models.TextField(
_(... | Python | 1 |
import re
from colorama import Fore
def preprocess_email(email_content):
"""
Preprocess the email content for machine learning models.
This includes extracting relevant features like links, suspicious keywords, etc.
Args:
email_content (str): The email body content.
Returns:
... | Python | 1 |
ent = new_client(api_url(wallet.public_key.network));
let (oui, commit, nonce, update) = match self {
Update::Routers(routers) => (
routers.oui,
routers.commit,
routers.nonce,
blockchain_txn_routing_v1::Update::UpdateRouters(UpdateRout... | Rust | 0 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# NO CHECKED-IN PROTOBUF GENCODE
# source: response_depth_by_order_updates.proto
# Protobuf Python Version: 6.31.0
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import de... | Python | 1 |
s='PQRS'
print([s[ind] for ind in range(len(s))]) | Python | 1 |
10),
page: Some(20),
},
)
.await;
}
}
use assert_cmd::Command;
const EXECUTABLE: &str = "portmanteau";
fn get_bin() -> Command {
Command::cargo_bin(EXECUTABLE).expect("Executable's name has changed?")
}
#[test]
fn version() {
get_bin()
.arg("-v")
... | Rust | 0 |
################################################################################
# SampleMove.py
# Copyright (c) 2017 Robert McNeel & Associates.
# See License.md in the root of this repository for details.
################################################################################
from Rhino import *
from Rhino.C... | Python | 1 |
// These are compiled to nothing if debug_assertions are off!
/// chek::debug_ge!(4, 3);
/// chek::debug_ge!(4, 4);
/// chek::debug_ge!(4, 3, "With a message");
/// chek::debug_ge!(4, 3, "With a formatted message: {}", "oh no");
/// ```
#[macro_export]
macro_rules! debug_ge {
($left:expr, $right:expr $(,)?) => ({
... | Rust | 0 |
supported by range query.", field_name)) }
};
let (value_type, left, right) = range.try_unwrap();
let query = RangeQuery::new_term_bounds(field, value_type, &left, &right);
wrap_query(Box::new(query))
}
fn new_facet_query(
index: RTantinyIndex,
field: RString... | Rust | 0 |
\"\"\n ], \n \"place\": [\n \"Простоквашино\", \n \"\"\n ]\n }\n }, \n {\n \"text\": \"Всё во имя Тебя, Хранитель! Удалось подменить список героев, чьим Духам-Хранителям должен был быть посвящён ритуал в одном из храмов Вилейки. Удалось добавить туда и нас ... | Python | 1 |
ie_id = ?', (movie_id,))
movie = cursor.fetchone()
conn.close()
return movie
# Функсияҳои рассылка
def save_broadcast_stats(post_content, post_type, file_id, sent_count, failed_count, total_count):
"""Захираи статистикаи рассылка"""
conn = sqlite3.connect('movies.db')
cursor = conn.cursor(... | Python | 1 |
ope_id: uint32_t,
}
pub type uint32_t = __uint32_t;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct in6_addr {
pub __in6_u: C2RustUnnamed_275,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union C2RustUnnamed_275 {
pub __u6_addr8: [uint8_t; 16],
pub __u6_addr16: [uint16_t; 8],
pub __u6_addr32: [uint32_t; 4],
}... | Rust | 0 |
import os
import sys
import time
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../')))
from sphero_sdk import SpheroRvrObserver
from sphero_sdk import RvrStreamingServices
rvr = SpheroRvrObserver()
def imu_handler(imu_data):
print('IMU data response: ', imu_data)
def color_det... | Python | 1 |
())
}
//! Polymorphically typed (Hindley-Milner) First-Order Term Rewriting Systems (no abstraction)
//!
//! Much thanks to:
//! - https://github.com/rob-smallshire/hindley-milner-python
//! - https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system
//! - (TAPL; Pierce, 2002, ch. 22)
use itertools::Itertools;
... | Rust | 0 |
= String::new();
let mut a = A(&mut x, &mut y);
let a = &mut a;
let mut c1 = move || {
a.0.truncate(0);
};
let mut c2 = move || {
a.1.truncate(0);
};
c1();
c2();
}
// Test that even if a path is moved into the closure, the closure is not FnOnce
// if the path is not... | Rust | 0 |
import logging
from unittest.mock import Mock, patch
import pytest
from imas_paraview import VTKHandler
@pytest.fixture
def mock_output_window():
with patch("imas_paraview.vtkhandler.win") as mock_vtk_win:
mock_output_window = Mock()
mock_vtk_win.GetInstance.return_value = mock_output_window
... | Python | 1 |
ATE_KEY,
None,
web30,
vec![],
)
.await
.expect("Failed to send tokens to Cosmos");
info!("Send to Cosmos txid: {:#066x}", tx_id);
check_send_to_cosmos_attestation(&mut grpc_client, erc20_address, dest, *MINER_ADDRESS).await;
let _tx_res = web30
.wait_for_transac... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier, plot_tree
train_file = 'experiment_04_training_set.csv'
test_file = 'experiment_04_testing_set.csv'
def read_data(filename: str) -> list[np.ndarray]:
data = np.loadtxt(filename, delimiter=',', skiprows=1)
x = ... | Python | 1 |
is the unique ID for your hardware as seen by the network. Obviously you might have a completely different view on things.
#[serde(rename = "imei", skip_serializing_if = "Option::is_none")]
pub imei: Option<String>,
/// Tags are metadata for the device that you can set. These are just strings.
#[serde(... | Rust | 0 |
def solve(grid):
p=len(grid)
freq={}
for i in range(p):
for j in range(p):
freq[grid[i][j]]=freq.get(grid[i][j],0)+1
m=min(freq.values())
c=min(k for k,v in freq.items() if v==m)
out=[[0]*(p*p) for _ in range(p*p)]
for i in range(p):
for j in range(p):
... | Python | 1 |
)
await process_compliments(BATCH_SIZE)
await process_tts(BATCH_SIZE)
except Exception as e:
logger.error(f"Error in process_pipeline: {str(e)}")
def handle_shutdown(sig, frame):
"""Handle shutdown signals gracefully."""
global running
logger.info(f"Received shutdown signal {sig... | Python | 1 |
et("ProductId")
self._DeviceName = params.get("DeviceName")
self._Payload = params.get("Payload")
memeber_set = set(params.keys())
for name, value in vars(self).items():
property_name = name[1:]
if property_name in memeber_set:
memeber_set.remove(p... | Python | 1 |
duce_mean(tf.to_float(tf.nn.in_top_k(class_logits, sparse_labels, 1)))
# self.d_loss_class = tf.Print(self.d_loss_class, [error_rate], "gpu " + str(gpu_idx) + " current minibatch error rate")
if gpu_idx == 0:
update = tf.assign(num_error_rate, num_error_rate + 1.)
with tf.control_dependencies([u... | Python | 1 |
import numpy as np
import cv2
from PIL import Image
#---------------------------------------------------------#
# 将图像转换成RGB图像,防止灰度图在预测时报错。
# 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB
#---------------------------------------------------------#
def cvtColor(image):
if len(np.shape(image)) == 3 and np.shape(image)[2] == ... | Python | 1 |
# stats
episode_data['Reached_target'] += info['Reached_target']
episode_data['Optimal_route'] += info['Optimal_route']
episode_data['Delay_exceeded'] += info['Delay_exceeded']
epi... | Python | 1 |
r(f"{request} has no response")
for candidate in response.candidates:
match candidate.finish_reason:
case None | FinishReason.STOP:
pass
case FinishReason.MAX_TOKENS:
if not request.return_incomplete_message:
... | Python | 1 |
of the cases is significant. They are sorted so that cmp::max
/// will keep the "more erroneous" of two values.
#[derive(Copy, PartialOrd, Ord, Eq, PartialEq, Debug)]
pub enum Representability {
Representable,
ContainsRecursive,
SelfRecursive,
}
/// Check whether a type is representable. This means it cann... | Rust | 0 |
from mmcls.models.backbones import GPViT
from ..builder import BACKBONES
@BACKBONES.register_module()
class GPViTDet(GPViT):
def __init__(self,
arch='',
img_size=224,
in_channels=3,
out_indices=-1,
drop_rate=0.,
... | Python | 1 |
# ------------------------------------------------------------------------------
#
# Project: pygeofilter <https://github.com/geopython/pygeofilter>
# Authors: Fabian Schindler <fabian.schindler@eox.at>
#
# ------------------------------------------------------------------------------
# Copyright (C) 2022 EOX IT Servic... | Python | 1 |
�', "wèi"),
('墜', "zhuì"),
('墝', "qiāo,qiào"),
('增', "zēng,zèng,céng"),
('墟', "xū"),
('墠', "shàn,chǎn"),
('墡', "shàn"),
('墢', "bá,fèi"),
('墣', "pú"),
('墤', "kuài,tuí"),
('墥', "dǒng,tuǎn"),
('墦', "fán,fān"),
('墧', "què,qiáo"),
('墨', "mò,mèi"),
('墩', "dūn"),
('墪... | Rust | 0 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
__all__ = []
adapter_host = None
"""The host on which adapter is running and listening for incoming connections
from the launcher and the servers."""
channel = Non... | Python | 1 |
import itertools
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import zmq
import math
print('Waiting to connect...')
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.setsockopt(zmq.SNDTIMEO, 5000)
socket.bind("tcp://*:5556")
num_points = int(socket.recv())
... | Python | 1 |
()
.collect();
if lines.len() == 1 {
return i32::from_str_radix(&lines[0], 2).unwrap();
}
assert!(!lines.is_empty());
}
panic!("not found");
}
fn part2(path: &str, digits: usize) -> io::Result<i32> {
let file = File::open(path)?;
let reader = BufReader... | Rust | 0 |
llets/file-bank/src/lib.rs<gh_stars>0
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::traits::{Currency, OnUnbalanced, ReservableCurrency, ExistenceRequirement::AllowDeath};
pub use pallet::*;
mod benchmarking;
pub mod weights;
use sp_runtime::{
RuntimeDebug,
traits::{AccountIdConversion, StaticLook... | Rust | 0 |
("season - winter <year>",
b.reg(r#"зим(?:ой|у)"#)?,
datetime_check!(form!(Form::Year(_))),
|_, year| Ok(helpers::year_month_day(year.value().form_year()?, 12, 21)?
.span_to(&helpers::year_month_day(year.value().form_year()? + (... | Rust | 0 |
Some(
"This is an example of a\n\
simple application.\n"
.to_string()
)
);
}
#[test]
fn parse_bin_and_example_bundles() {
let toml_str = "\
[package]\n\
name = \"example\"\n\
version = \"0.1.0\"\n\
description = \"An ... | Rust | 0 |
#[test]
fn url_in_query() {
let url = Url::parse("https://accounts.google.com/ServiceLogin?hl=de&passive=true&continue=https://www.google.com/&ec=GAZAAQ").unwrap();
let path = url_to_path(&url).unwrap();
assert_eq!(
PathBuf::from("accounts.google.com/... | Rust | 0 |
lSoup(content, "html.parser")
else:
soup = self.soup
elements = soup.find_all(**search_args)
logger.debug(f"{len(elements)} 個の <{tag}> 要素が見つかりました。")
for i, elem in enumerate(elements, 1):
logger.debug(f"要素 {i}: {elem.get_text()[:50]}...")
return elements
... | Python | 1 |
,
// 5.0,
// 5.0,
// );
// draw_text_left(
// 1,
// &format!(
// "B Button is{:?}Key",
// keys(&Control::B).expect("Could not get keys for B button")
// ),
// &Message::White,
// 125.0,
... | Rust | 0 |
Self {
segment: self.segment.split_range(t_range),
}
}
#[inline]
pub fn split(&self, t: T::Scalar) -> (Self, Self) {
let (a, b) = self.segment.split(t);
(Self { segment: a }, Self { segment: b })
}
#[inline]
pub fn before_split(&self, t: T::Scalar) ->... | Rust | 0 |
nter = area.rect.left_top + pos.center
avatar_rect = Rect(center.x - 42, center.y - 100, center.x + 55, center.y - 10)
avatar_part = cv2_utils.crop_image_only(screen, avatar_rect)
# cv2_utils.show_image(avatar_part, wait=0)
source_kps, source_desc = cv2_ut... | Python | 1 |
}
/// Struct of tags.
#[derive(Debug, Clone, Default)]
pub struct Tags {
/// Contents of the id tag if present.
pub id: Option<String>,
/// Contents of the msg-id tag if present.
pub msg_id: Option<String>,
/// The display name of the user.
pub display_name: Option<String>,
/// The ID of t... | Rust | 0 |
quote! {<#ty>::binprot_shape() }
});
quote! {binprot::Shape::Tuple(vec![#(#fields,)*])}
}
syn::Fields::Unit => {
unimplemented!()
}
}
}
syn::Data::Enum(DataEnu... | Rust | 0 |
to retrieve the number of "
warnMsg += "roles for user '%s'" % user
logger.warning(warnMsg)
continue
infoMsg = "fetching roles for user '%s'" % user
logger.info(infoMsg)
roles = set()
indexRang... | Python | 1 |
use std::fs::File;
use std::io::prelude::*;
fn read_input() -> String {
let filename = "input.txt";
match File::open(filename) {
Ok(mut file) => {
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
content
}
Err(error) => {
... | Rust | 0 |
sforms(images)
>>> targets = transforms(images)
>>>
>>> # feed through PMSN model
>>> anchors_out = model(anchors)
>>> targets_out = model.target(targets)
>>>
>>> # calculate loss
>>> loss = loss_fn(anchors_out, targets_out, prototypes=model.prototypes)
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.