text string | label_name string | labels int64 |
|---|---|---|
of_month=15)),
("SME-1", offsets.SemiMonthEnd(day_of_month=1)),
("SME-27", offsets.SemiMonthEnd(day_of_month=27)),
("SMS-2", offsets.SemiMonthBegin(day_of_month=2)),
("SMS-27", offsets.SemiMonthBegin(day_of_month=27)),
],
)
def test_anchored_shortcuts(shortcut, expected):
result ... | Python | 1 |
import pandas as pd
# Get the new end of season stats for each team (no duplicates)
# The data structure was changed from Training_Schedule csv's, this is using the new data structure
def get_new_standings():
# Load the training data
df = pd.read_csv('./backend/data/Schedule_Stats.csv').drop(columns=['game_id... | Python | 1 |
}
}
}
<reponame>bitcoinmw/bitcoinmw
// Copyright 2021 The BitcoinMW Developers
//
// 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/LICENS... | Rust | 0 |
ace_blowup: usize,
/// Seed value for random evaluation.
seed: FieldElement,
/// Evaluation nodes in causal order.
nodes: Vec<Node>,
/// Current row
row: usize,
}
/// Node in the evaluation graph.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Node {
/// The operation represented b... | Rust | 0 |
.1", VersionedDocsLink::None),
("v0.5.0", VersionedDocsLink::None),
("v0.5.0-beta.1", VersionedDocsLink::None),
("v0.5.0-beta.0", VersionedDocsLink::None),
];
#[component(VersionedDocsLinkView<G>)]
fn versioned_docs_link_view(
(name, versioned_docs_link): (&'static str, &'static VersionedDocsLink),
) -... | Rust | 0 |
f_a = FooA;
/// let foo1 = Foo { a: 20 };
/// let foo2 = Foo { a: 10 };
/// assert_eq!(f_a.value(&foo1), &20i32);
/// assert_eq!(f_a.apply_sorter(&Compare, &foo1, &foo2), Ordering::Greater);
/// ```
pub trait Accessor<R>: Clone {
type Value;
/// Return a reference to a member of `data`
fn value<'a>(&self, d... | Rust | 0 |
);
let addr = rs.next().unwrap();
let port = match rs.next() {
Some(ps) => ps.parse::<u16>().map_err(|e| {
io::Error::new(io::ErrorKind::Other, e)
}),
None => Ok(DEFAULT_PORT),
}?;
Ok((addr, port))
}
pub struct New<A: Api> {
phantom: PhantomData<A>,
}
impl<A: Api... | Rust | 0 |
me(), Value::U64(value)))
}
fn record_bool(&mut self, field: &Field, value: bool) {
self.0
.insert(KeyValue::new(field.name(), Value::Bool(value)))
}
fn record_str(&mut self, field: &Field, value: &str) {
self.0.insert(KeyValue::new(field.name(), value))
}
fn recor... | Rust | 0 |
rest().to_owned();
let guild = match msg.guild() {
Some(val) => val,
None => return Err(CommandError::from(get_msg!("error/no_guild"))),
};
// check if it starts with a code block
if raw_json.starts_with("```") && raw_json.ends_with("```") {
// remove code block from string
... | Rust | 0 |
# 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 agreed to in writing, s... | Python | 1 |
of hashes to address any content. It utilizes
//! [Blake2b](https://www.blake2.net/) as hashing algorithm. Holochain hashes
//! have a length of 39 bytes, made up of 3 bytes for identifying the hash, 32
//! bytes of digest and 4 location bytes. The complete scheme of a hash in byte
//! format is:
//!
//! ```text
//! <h... | Rust | 0 |
import boto3
import os
import json
from typing import List
s3 = boto3.resource('s3')
bucket = s3.Bucket(os.environ["BUCKET_NAME"])
def get_config(chat_id):
'''Gets config and model from s3 by chat_id'''
try:
config = bucket.Object(f"{chat_id}-config.json").get()['Body'].read().decode('utf-8')
... | Python | 1 |
ld_size = int(os.environ['WORLD_SIZE'])
# args.gpu = int(os.environ['LOCAL_RANK'])
# elif 'SLURM_PROCID' in os.environ:
# args.rank = int(os.environ['SLURM_PROCID'])
# args.gpu = args.rank % torch.cuda.device_count()
# else:
# print('Not using distributed mode')
# args.di... | Python | 1 |
agfun3(_key: &Value, src: &[(&Value, Weight)]) -> Value {
Value::u64(src.len() as u64)
}
fn gfun4(v: Value) -> Option<(Value, Value)> {
Some((v.clone(), v))
}
fn agfun4(key: &Value, _src: &[(&Value, Weight)]) -> Value {
key.clone()
}
fn ffun(v: &Value) -> bool {
... | Rust | 0 |
import csv
import json
from bs4 import BeautifulSoup
from SourceFolder.OpenAi.StackOverflow.StackOverflow2013.Results.DR1_CSV4 import input_csv
def clean_html(html_str):
if not html_str or not html_str.strip():
return ""
try:
soup = BeautifulSoup(html_str, "html.parser")
return soup.g... | Python | 1 |
allow(clippy::cast_sign_loss)]
fn mutate(
&mut self,
state: &mut S,
input: &mut I,
_stage_idx: i32,
) -> Result<MutationResult, Error> {
if input.bytes().is_empty() {
Ok(MutationResult::Skipped)
} else {
let idx = state.rand_mut().below(inp... | Rust | 0 |
import sys
input = sys.stdin.readline
l = int(input())
nums = list(map(int, input().split()))
n = int(input())
nums.sort()
if n in nums:
print(0)
else:
min_val = 0
max_val = 0
for num in nums:
if num < n:
min_val = num
elif num > n and max_val == 0:
max_val = num
max_val -= 1
min_val += 1
print... | Python | 1 |
Imprimir números pares: Peça ao usuário um número inteiro positivo N. Use um while para imprimir todos os números pares de 0 até N (inclusive, se for par). | Python | 1 |
env!(context.is_view(false).build());
contract.update_settings(
None,
Some(30_000_000_000),
None,
None,
None,
None,
None,
None,
None,
);
testing_env!(context.is_view(true).build());
... | Rust | 0 |
t (indentStack and curCol in indentStack):
raise ParseException(s, l, "not an unindent")
if curCol < indentStack[-1]:
indentStack.pop()
NL = OneOrMore(LineEnd().set_whitespace_chars("\t ").suppress())
INDENT = (Empty() + Empty().set_parse_action(checkSubIndent)).set_name("INDENT... | Python | 1 |
要的列存在
required_columns = ['title', 'bvid', 'duration', 'tag_name', 'author_name']
for col in required_columns:
if col not in columns:
raise ValueError(f"Required column '{col}' not found in table {table_name}")
# 获取视频观看次数统计
cursor.execute(f"""
SELECT
title,
... | Python | 1 |
tion as e:
# make sure threads are killed to avoid being stuck,
# e.g. after a KeyboardInterrupt, then re-raise
try:
kill_switch.set()
except queue.Full:
pass
for worker in workers:
... | Python | 1 |
}
_ => {
let (unlocked, locked) = resp.body.parser().get2::<Vec<
rustbus::wire::marshal::traits::ObjectPath<&str>,
>, Vec<
rustbus::wire::marshal::traits::ObjectPath<&str>,
>>().unwrap();
println!("Items found: (unlocked){:... | Rust | 0 |
#!/usr/bin/env python
import os.path
from setuptools import setup
__version__ = "can't find version.py"
exec(compile(open('rasl/version.py').read(), # pylint: disable=exec-used
'rasl/version.py', 'exec'))
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup... | Python | 1 |
## obviously need to figure out how to do this in a more organized way
builtin = {}
## for example:
#import msisection3step
#app = msisection3step.app
#nodes = msisection3step.nodespecs
#bindings = msisection3step.bindingspecs
#builtin[app['name']] = {'application': app, 'nodes': nodes, 'bindings': bindings}
| Python | 1 |
header_banner="Combined indicator signal functions",
extra_top="from .combined_calcs import * # If used as a package\ntry:\n from combined_calcs import * # If run as flat files\nexcept Exception:\n pass\n",
)
Path(args.out_signals).write_text(signals_code, encoding="utf-8")
print(f"Wro... | Python | 1 |
re(mesh.clone(), quadrature);
let u = DVector::zeros(model.ndof());
let a_coo_csr = model.assemble_stiffness(&u, &material).to_csr(Add::add);
let mut a_csr = a_coo_csr.clone();
a_csr.transform_values(|_, _, val| *val = 0.0);
model.assemble_stiffness_into(&mut a_csr, &u, &material);
assert_eq!... | Rust | 0 |
if proc.returncode:
# CC --version failed: ignore error
return
text = stdout.splitlines()[0]
text = normalize_text(text)
info_add('CC.version', text)
def collect_info(info):
error = False
info_add = info.add
for collect_func in (
# collect_os() should be the first, t... | Python | 1 |
print("Cauculadora da Fórmula de Bhaskara: ")
valora = float(input("Digite o valor de a: "))
valorb = float(input("Digite o valor de b: "))
valorc = float(input("Digite o valor de c: "))
while valora == 0:
print("O coeficiente a não pode ser igual a zero.")
valora = float(input("Digite o valor de a: "))
di... | Python | 1 |
/testkey1", ctx.server_addr).as_str(),
StatusCode::OK,
)
.await;
assert_eq!(config.key, "testkey1");
assert_eq!(config.value, "testvalue1");
let db_configs = sqlx::query_as!(
UserConfigDto,
"SELECT key, value FROM user_configs AS c JOIN users AS u ON u.id = c.user_id WHERE u... | Rust | 0 |
::parse(u).unwrap())
.collect::<Vec<_>>(),
)
.unwrap();
assert_eq!(result, PathBuf::from(expected));
}
}
#[test]
fn test_remote_specifiers_to_paths() {
run_remote_specifiers_to_paths_test(
&[
"http://localhost/file.json",
"http://localhost/file.ts",
... | Rust | 0 |
vec![
Stmt::BindingDef(BindingDef {
name: "baz".to_string(),
val: Expr::BindingUsage(BindingUsage {
name: "foo".to_string(),
}),
}),
Stmt::Expr(Expr::BindingUs... | Rust | 0 |
import sys
import joblib
import os
path = "F:\\Sanchalak\\test\\features_extraction.py"
if os.path.exists(path):
pass
else:
print("file not present")
print(os.listdir())
sys.path.append("F:\\Sanchalak")
import numpy as np
from sanchalak import features_extraction
def predict(test_url):
features_test =... | Python | 1 |
g_table: Arc<RoutingTable>,
subnet_records: Arc<BTreeMap<SubnetId, SubnetType>>,
) -> Self {
Self::ReplyCallback {
time,
incoming_payload,
incoming_cycles,
call_context_id,
response_data: vec![],
response_status: if replied {
... | Rust | 0 |
is not active after this number of seconds.
Default: :py:attr:`pywinauto.timings.Timings.window_find_timeout`.
:param retry_interval: How long to sleep between each retry.
Default: :py:attr:`pywinauto.timings.Timings.window_find_retry`.
"""
if timeout is None:
... | Python | 1 |
# 1) Define four functions: add, subtract, divide, and multiply.
# Each function should take two arguments, and they should print
# the result of the arithmetic operation indicated by the function name.
# When orders matters for an operation, the first argument should be treated as the left operand,
# and the second ar... | Python | 1 |
("\u{03B5}\u{03C0}\u{03B5}", 7, 1, None),
Among("\u{03BC}\u{03B5}\u{03C4}\u{03B5}\u{03C0}\u{03B5}", 8, 1, None),
Among("\u{03B5}\u{03C3}\u{03B5}", -1, 1, None),
Among("\u{03BA}\u{03BB}\u{03B5}", -1, 1, None),
Among("\u{03B5}\u{03C3}\u{03C9}\u{03BA}\u{03BB}\u{03B5}", 11, 1, None),
Among("\u{03B5}\u{0... | Rust | 0 |
ValueError
If ``n`` < 0 or ``prec`` < 0.
Or ``n`` or ``prec`` is not an integer.
Examples
========
>>> from sympy.ntheory.bbp_pi import pi_hex_digits
>>> pi_hex_digits(0)
'3243f6a8885a30'
>>> pi_hex_digits(0, 3)
'324'
These are consistent with the following results
... | Python | 1 |
text_squares.push(new_square.with_new_bind_group_and_buf(device, local_bind_group_layout));
}
}
};
squares[1].0.set_pos(save.x_start as f32, save.y_start as f32);
squares[1].0.set_siz(save.x_increment as f32, save.y_increment as f32);
let mut collide = false;
let mut entering_tex... | Rust | 0 |
'''
The MIT License(MIT)
Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
... | Python | 1 |
), "val1".as_bytes(), ValueType::TypeValue),
("hba".as_bytes(), "val2".as_bytes(), ValueType::TypeValue),
];
let t8 = write_table(&env, f8, 3, 8);
let f9: &[(&[u8], &[u8], ValueType)] = &[
("iaa".as_bytes(), "val1".as_bytes(), ValueType::TypeValue),
("iba".as_... | Rust | 0 |
d(map) => KeysIter::Hashed(map.keys_from(&key)),
},
};
Ok(handle::to_handle(iter))
});
utils::unwrap_exc_or_default(&env, res)
}
/// Returns the pointer to the iterator over map values starting at the given key.
#[no_mangle]
pub extern "system" fn Java_com_exonum_binding_core_storag... | Rust | 0 |
dicators: {e}")
return {"error": str(e)}
def save_models(self):
"""Save trained models"""
try:
# Save scaler
joblib.dump(self.scaler, os.path.join(self.models_dir, 'bayesian_scaler.pkl'))
# Save model parameters
model_para... | Python | 1 |
T: &str = "http://localhost:50051";
async fn create_slurm_scheduler() -> Result<Scheduler> {
let credential = Credential::new_password(String::from("<PASSWORD>"), String::from("<PASSWORD>"));
create_slurm_scheduler_inner(credential).await
}
async fn create_slurm_scheduler_inner(credential: Credential) -> Resu... | Rust | 0 |
class NotAnObject:
def __repr__(self):
return "NAO"
NAO = NotAnObject()
| Python | 1 |
# Copyright (c) 2024-Present
# Author: Jiawei Zhang <jiawei@ifmlab.org>
# Affiliation: IFM Lab, UC Davis
###############################################
# Multi-Head & Multi-Channel Fusion Functions #
###############################################
r"""
This module provides the "fusion functions" that can be used to... | Python | 1 |
from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.tools import YouTubeSearchTool
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPREC... | Python | 1 |
assert np.allclose(
x[:, 0].l.records["level"].to_numpy(), [-1e10] * 5
) # bigM threshold
assert model.status == ModelStatus(1)
assert model.objective_value == 73.63
def test_gradient_boosting_valid_variable_no_ub(data_gbt):
m, ensemble, _, in_data, _, _, par_input, _, [learning_rate, bias... | Python | 1 |
# --------------------------------------------------
# File Name : 2567_1_Q4_A3-S.py
# Problem : MCQ
# Author : Worralop Srichainont
# Date : 2025-07-29
# --------------------------------------------------
# Input solution answer of the exam
solution_answer = input().strip()
# Input score gained or deducted... | Python | 1 |
let corners_heuristic = CornerHeuristic::new();
corners_heuristic.save("./data/corners_heuristic.bin");
}
}
}
use chrono::Duration;
use crate::checks;
use super::*;
/// Ban one or more users from the server. use `delban` to also delete the messages he sent within the last day.
#[command]
#[us... | Rust | 0 |
arr, bail, bail_at, ensure, error, macro_no_op, stock_syms::*, str, Arr, Callable, DequeAccess,
DequeOps, EnvMode, FromVal, GResult, RGlobal, Rest, Root, Span, Sym, Val,
};
use glsp_proc_macros::backquote;
use smallvec::SmallVec;
use std::collections::{
hash_map::Entry::{Occupied, Vacant},
HashMap, Hash... | Rust | 0 |
eeded_money = 15 - self.money
if self.bank.money >= needed_money:
self.bank.loan(self, needed_money)
if self.model.schedule.time == 14 * 4: # 14 months
self.buy_house()
class Government(mesa.Agent):
money = 500
def __init__(self, unique_id, model):... | Python | 1 |
eAcctType(self, SettleAcctType):
self._SettleAcctType = SettleAcctType
@property
def IdType(self):
"""证件类型,见《证件类型》表
:rtype: str
"""
return self._IdType
@IdType.setter
def IdType(self, IdType):
self._IdType = IdType
@property
def IdCode(self):
... | Python | 1 |
# ----------------------------------------------------------------------
# Utilities: Translations - Translate
# Copyright (C) 2018-2025 Ye Lei (叶磊)
#
# 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 Founda... | Python | 1 |
ddr & 0xfffc {
0x0 => self.msip[0],
0x4 => self.msip[1],
0x8 => self.msip[2],
0xc => self.msip[3],
0x10 => self.msip[4],
0x4000 => (self.mtimecmp[0] & 0xffffffff) as u32,
0x4004 => ((self.mtimecmp[0] >> 32) & 0xffffffff) as u32,
... | Rust | 0 |
0x8, 0x3, 0xd, 0x7, 0x2, 0xf, 0xa, 0xd, 0x4, 0xc,
// 0xf, 0x8, 0xa, 0x5, 0xd, 0x7, 0xe, 0xf, 0xa, 0x0, 0xc, 0x0, 0x8, 0x9, 0x6, 0x2,
// 0xa, 0x7, 0x7, 0xc, 0x8, 0x1, 0x9, 0x5, 0x6, 0x6, 0xd, 0xe, 0x4, 0x1, 0xc, 0xe,
// 0x9, 0x3, 0x6, 0x6, 0x1, 0x9, 0x2, 0xc, 0x8, 0x3, 0xa, 0x3, 0x7, 0xc, 0x0, 0x6,... | Rust | 0 |
extern "C" {
pub fn xmlCleanupCharEncodingHandlers();
}
extern "C" {
pub fn xmlRegisterCharEncodingHandler(handler: xmlCharEncodingHandlerPtr);
}
extern "C" {
pub fn xmlGetCharEncodingHandler(enc: xmlCharEncoding) -> xmlCharEncodingHandlerPtr;
}
extern "C" {
pub fn xmlFindCharEncodingHandler(
name: *const :... | Rust | 0 |
me']
#if 'resolved_placename' not in r.keys() and 'name' in r.keys():
# r['resolved_placename'] = r['name']
# del r['name']
if 'name' in r.keys():
r['resolved_placename'] = r['name']
del r['name']
s... | Python | 1 |
import streamlit as st
import yfinance as yf
def fetch_and_display_stock_price(stock_symbol):
try:
stock = yf.Ticker(stock_symbol)
quote = stock.history(period="1d")
if not quote.empty:
price = quote["Close"].iloc[-1]
if ".BO" in stock_symbol or ".NS" in stock_symbo... | Python | 1 |
host_metrics,
)
}
pub(crate) async fn process_trigger(
&self,
logger: &Logger,
block: &Arc<LightEthereumBlock>,
trigger: EthereumTrigger,
state: BlockState,
proof_of_indexing: SharedProofOfIndexing,
) -> Result<BlockState, MappingError> {
... | Rust | 0 |
am_id: 4,
data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
},
frame::Frame::Stream {
stream_id: 8,
data: stream::RangeBuf::from(b"a", 0, false),
},
frame::Frame::ResetStream {
stream_id: 8,
... | Rust | 0 |
'''
Escribir un programa que pregunte el nombre del usuario
en la consola y después de que el usuario lo introduzca muestre por pantalla
<NOMBRE> tiene <n> letras, donde <NOMBRE> es el nombre de usuario en mayúsculas y <n> es el
número de letras que tienen el nombre.
'''
NOMBRE = input("anexa tu nombre aqui: ")
prin... | Python | 1 |
from .. import Provider as AutomotiveProvider
class Provider(AutomotiveProvider):
"""Implement automotive provider for ``da_DK`` locale.
Source: https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Denmark
"""
license_formats = ("?? ## ###",)
| Python | 1 |
e_dir_all(&report_path)?;
for address in addresses {
get_diff_from_address(address, &spec_path, &out, &report_path, &mut diff_ratio_list, &mut stdout).await?;
}
let avg_ratio:f32 = diff_ratio_list.iter().sum::<f32>() / diff_ratio_list.len() as f32;
println!("The avg_ratio is: {:.2}%", avg_ratio... | Rust | 0 |
drop_rate=0,
decoder_attention_type=None,
encoder_norm_layer="abn",
encoder_norm_act="relu",
decoder_norm_layer="abn",
decoder_norm_act="relu",
sigmoid_init=True,
**encoder_params,
):
if output_stride != 32:
encoder_params["output_stride"... | Python | 1 |
from functools import partial
# IF you change the base image, you need to rebuild all images (run with --force_rebuild)
_DOCKERFILE_BASE = r"""
FROM --platform={platform} ubuntu:22.04
ARG DEBIAN_FRONTEND=noninteractive
ENV TZ=Etc/UTC
RUN apt update && apt install -y \
wget \
git \
build-essential \
libffi-dev \
libt... | Python | 1 |
# Atividade 06:
# Soma de Números Positivos:
# Escreva um programa que solicite números ao usuário até
# que ele digite um número negativo, somando apenas os
# números positivos inseridos.
s = 0
n = 0
while True:
n = int(input('Digite: '))
if n 0:
s = n + n
break
print(f'Acabou {s}') | Python | 1 |
*const PolyComm<GAffine>,
rc_c: *const PolyComm<GAffine>,
) -> *const DlogVerifierIndex<'a, GAffine> {
let srs: SRS<GAffine> = (unsafe { &*urs }).clone();
let index = DlogVerifierIndex::<GAffine> {
domains: EvaluationDomains::create(variables, constraints, public_inputs, nonzero_entries)
... | Rust | 0 |
| | x = 8 |
/// +-------+ +-------+
/// | |
/// v v
/// +-6-----+
/// | k = a |<-+
/// +-------+ |
/// | | |
/// +----+ | |
/// | v |
/// | +-7-----+ |
/// | | b = 2 | |
/// | +-------+ |
/// | | |
/// | ... | Rust | 0 |
(light_data >= 1048) && (light_data < 3048) {
2
} else if (light_data >= 3048) && (light_data < 3948) {
3
} else {
4
};
//finally paint the one led wherever the position is
let _ = neopixel.write(brightness(
(0..NUM_LEDS).map(|i| i... | Rust | 0 |
import shelve
from datetime import datetime
def get_upcoming_scheduler_tasks(path='celerybeat-schedule'):
"""
Retrieves a sorted list of upcoming tasks scheduled in a shelve database.
The function opens a shelve database, reads the scheduled tasks, calculates
the next run time for each task based on ... | Python | 1 |
or.clone()),
),
),
)
.with_shared_property(icon)
.with_shared_property(label)
.with_shared_property(selector)
.with_property(Selected(false))
.with_debug_name("CheckBox")
}
}
use glfw::{Action, Key, M... | Rust | 0 |
= geometry::Point2::new(wire.start.x, wire.start.y);
let end = geometry::Point2::new(wire.end.x, wire.end.y);
let color = match wire.kind {
WireType::Wire => drawing::Color::new(0.0, 0.28, 0.0, 1.0),
WireType::Dotted => drawing::Color::new(0.0, 0.0, 0.48, 1.0),
_ => ... | Rust | 0 |
if m != i && n != j {
cofactor_row.push(matrix[m][n]);
}
}
if cofactor_row.len() != 0 {
cofactor.push(cofactor_row.clone());
cofactor_row.clear();
}
}
// List of determinants for cofactor matrixes
let der = match get_determinant(&cofactor) {
Ok(determinant) => determina... | Rust | 0 |
e"><div class="highlight"><pre><span></span><spanclass="hlw"></span><span class="hlk">fn</span> <span class="hlnf">
main</span><span class="hlp">()</span><span class="hlw"> </span><span class="hlp">{</span><span class="hlw"></span>\n<span class="hlw">
</span><span class="hlfm">println!</span><span class... | Python | 1 |
test_dict = {'month': [1, 2, 3], 'name': ['Jan', 'Feb', 'March']}
res = {test_dict['month'][i]: test_dict['name'][i] for i in range(len(test_dict['month']))}
print("Flattened dictionary:", res)
| Python | 1 |
CHandleType_MONO_GC_HANDLE_WEAK_TRACK_RESURRECTION: MonoGCHandleType = 1;
pub const MonoGCHandleType_MONO_GC_HANDLE_NORMAL: MonoGCHandleType = 2;
pub const MonoGCHandleType_MONO_GC_HANDLE_PINNED: MonoGCHandleType = 3;
pub const MonoGCHandleType_MONO_GC_HANDLE_TYPE_MAX: MonoGCHandleType = 4;
pub type MonoGCHandleType = ... | Rust | 0 |
.path.join(pic_dir, pie_filename), '每种 xVyA 组合的出现次数')
plot_bar(itag_pair_count, os.path.join(pic_dir, itag_bar_filename), '每种 V:itag/A:itag组合的出现次数')
plot_pie(itag_pair_count, os.path.join(pic_dir, itag_pie_filename), '每种 V:itag/A:itag组合的出现次数')
plot_bar(chunk_num, os.path.join(pic_dir, chunk_bar_... | Python | 1 |
def read_triples(file_path):
"""从文件中读取三元组数据"""
triples = []
entities = set()
relations = set()
with open(file_path, 'r', encoding='utf-8') as file:
for line in file:
parts = line.strip().split()
if len(parts) == 3:
triples.append((parts[0], parts[... | Python | 1 |
r encryption key could not be obtained.
pub const FVE_DRY_RUN_FAILED : NtStatus = NtStatus::from_constant(0xC021001E); // STATUS_FVE_DRY_RUN_FAILED
/// The metadata disk region pointer is incorrect.
pub const FVE_BAD_METADATA_POINTER : NtStatus = NtStatus::from_constant(0xC021001F); // STATUS_FVE_BAD_METADATA_POINTER
... | Rust | 0 |
)
}
#[test]
fn segment_visible_both_ends_inside_fov() {
let fov = Fov {
vertex: Point2::new(0.0, 0.0),
center_angle: 34f32.to_radians(),
view_angle: 70f32.to_radians(),
};
let seg = Segment2::new(Point2::new(1, -1), Point2::new(0, -1));
assert!(fov.segment_visible(&seg))
}
... | Rust | 0 |
import discord
import random
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='$', intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user} Yardıma hazırım')
@bot.command()
async def çevre(ctx):
Önerme = ... | Python | 1 |
ef(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `OUTFIFO_CNT_CH2` reader - The register stores the byte number of the data in L1 Tx FIFO for Tx channel 2."]
pub struct OUTFIFO_CNT_CH2_R(crate::FieldReader<u8, u8>);
impl OUTFIFO_CNT_CH2_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Sel... | Rust | 0 |
"""An example that uses the .NET Kinesis Libraries to connect to a KST."""
import os
import time
import sys
import clr
# Add References to .NET libraries
clr.AddReference("C:\\Program Files\\Thorlabs\\Kinesis\\Thorlabs.MotionControl.DeviceManagerCLI.dll")
clr.AddReference("C:\\Program Files\\Thorlabs\\Kinesis\\Thorlab... | Python | 1 |
__darwin_size_t = libc::c_ulong;
pub type size_t = __darwin_size_t;
/* SRC_DATA is used to pass data to src_simple() and src_process(). */
#[derive ( Copy , Clone )]
#[repr(C)]
pub struct SRC_DATA {
pub data_in: *const libc::c_float,
pub data_out: *mut libc::c_float,
pub input_frames: libc::c_long,
pub... | Rust | 0 |
ports generating random numbers with a uniform
//! distribution around a given [`NonZero`] modulus.
//!
//! ```
//! # #[cfg(feature = "rand")]
//! # {
//! use crypto_bigint::{NonZero, RandomMod, U256, rand_core::OsRng};
//!
//! let modulus = NonZero::new(U256::from(3u8)).unwrap();
//! let n = U256::random_mod(&mut OsRn... | Rust | 0 |
Iso_8859_2 => "ISO-8859-2",
Iso_8859_3 => "ISO-8859-3",
Iso_8859_4 => "ISO-8859-4",
Iso_8859_5 => "ISO-8859-5",
Iso_8859_6 => "ISO-8859-6",
Iso_8859_7 => "ISO-8859-7",
Iso_8859_8 => "ISO-8859-8",
Iso_8859_9 => "ISO-8859-9",
... | Rust | 0 |
# dumb PDF template post processor:
# fills /Length, xref, startxref pointer, /Size from basic PDF templates
# doesn't support non-contiguous objects
# Ange Albertini
import sys
# usage: template.py <template text> <output pdf>
d = open(sys.argv[1], "rb").read()
out = open(sys.argv[2], "wb")
XREF_COUNT = "0 %i"
XR... | Python | 1 |
packet, round)
return receive_success
def record_block_propagation_time(self, block_packet: BlockPacketTpNet, r):
'''calculate the block propagation time'''
bp = block_packet
rn = len(set(bp.received_miners))
mn = self.MINER_NUM
def is_closest_to_percentage(a, b, pe... | Python | 1 |
let mut addr2 = Inet4SockAddr::new(Inet4Addr::LOCALHOST, 0);
addr2.set_ip(Inet4Addr::new(1, 2, 3, 4));
addr2.set_port(80);
assert_eq!(addr, addr2);
assert_eq!(addr.0, addr2.0);
}
#[test]
fn test_inet4addr_parse() {
use core::str::FromStr;
assert_eq!(... | Rust | 0 |
.emit(ipfs.cid_cat(cid).await) }
});
}
/// Append audio and video segments to the buffers.
fn append_buffers(&self, response: Result<(Vec<u8>, Vec<u8>)>) {
let (mut aud_seg, mut vid_seg) = match response {
Ok((a, v)) => (a, v),
Err(e) => {
ConsoleServ... | Rust | 0 |
t self.check_prerequisites():
raise Exception("前置条件检查失败")
# 2. 创建维护页面
self.create_maintenance_page()
# 3. 停止应用
self.stop_application()
# 4. 备份数据库
backup_file = self.backup_database()
... | Python | 1 |
# Update current second based on elapsed time
elapsed_time = time.time() - start_time
current_second = int(start_time + elapsed_time)
# Update packets received count for the current second
if curr... | Python | 1 |
import json
import os
class AssistantConfig:
def __init__(self, tools_to_use=None):
self.tools_to_use = tools_to_use or []
self.instructions_for_assistant = 'Use the tools to accomplish the task'
self.files_for_assistant = [] # Local file paths
self.assistant_details = self._build_... | Python | 1 |
3e => Operator::I64Store32 {
memarg: self.read_memarg()?,
},
0x3f => {
let (mem_byte, mem) = self.read_first_byte_and_var_u32()?;
Operator::MemorySize { mem_byte, mem }
}
0x40 => {
let (mem_byte, mem) = self.... | Rust | 0 |
fn remove_issuer(origin, entity_id: H256, issuer_id: T::AccountId) {
let sender = ensure_signed(origin)?;
ensure!(<OfficalAccountsIndex<T>>::contains_key(&sender), "You do not have permission to do this opertion!");
// remove from issuer list if exist
let mut entity_issuers = Self::entity_issuers(entity_id... | Rust | 0 |
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
ans = 0
count = collections.Counter()
for domino in dominoes:
key = min(domino[0], domino[1]) * 10 + max(domino[0], domino[1])
ans += count[key]
count[key] += 1
return ans
| Python | 1 |
nsformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES,
}
# This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any
# `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`).
SPECIAL_TASK_GUIDE_TO_MODEL_TYPES = {
"summari... | Python | 1 |
from selenium.webdriver.common.by import By
class OrderPageLocators:
# Заголовок страницы заказа
order_header = (By.XPATH, ".//div[text()='Для кого самокат']")
# Данные человека
name_field = (By.XPATH, ".//input[contains(@placeholder,'* Имя')]")
surname_field = (By.XPATH, ".//input[contains(@plac... | Python | 1 |
let client = reqwest::blocking::Client::new();
let endpoint = util::get_random_node_endpoint(handle, &mut rng);
util::block_on(endpoint.assert_ready(ctx));
let canister_id = CanisterId::from_u64(123456789);
for e in ENDPOINTS {
// Specifying a bogus content type should result in a 415.
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.