text string | label_name string | labels int64 |
|---|---|---|
e density at initialization. It is
recommended to choose a large enough scale factor such that most values
initially lie within a region of high likelihood. This improves
training.
"""
self.cdf_logits = MonotonicMLP(rng, num_pdfs, num_units, init_scale)
class PeriodicFourierEntropyMode... | Python | 1 |
obj.get("type") is not None else 'direct',
"ocr": PartialDirectConversionParametersOcr.from_dict(obj["ocr"]) if obj.get("ocr") is not None else None,
"assemble": PartialDirectConversionParametersAssemble.from_dict(obj["assemble"]) if obj.get("assemble") is not None else None,
"metada... | Python | 1 |
import requests
import ujson as json
import sys
import binascii
to_address = "TRTLv3xYqUdAy4K8viYjNnMj21NLohHbf9ut2Cczxyh96d74TzxNgdB3aZbb9U2ZJ1DVmVpbDwzH77821o9ciNYQVaSt3V6bu7R"
content = """
_____ ____
/ \ | o |
| |/ ___\|
|_________/
|_|_| |_|_|
"""
def rpc(method, params={}):
base_url = "... | Python | 1 |
\x10iqD\xb2\xca\xbf\xc3\xbb\xe7\xff\x00\x0a\x99D\
\xcb\xda\xc6?\x13\xbb8\x8b\xaf\x8a\xb1E*\xad\x9cM\
+\x7f\x0a\xed\xddW\xff\x00\xb7\xae\xb5\xe9V[\xf5\xba\
m\xa86\xc6>\xef\xb0\xc0\xadq\xe1}6\xc2\xfd\xbc\
\xa5\xb7\x89W\xf8\xb8\xddW-u\xed\x0fK\xde\xd2\xcb\
\x13m\xfe\x15aGmJ\xf7y|\xcc\xb9b\xb8\xd6\
m<\xab{V\xb5\x8b\xee\xfc... | Python | 1 |
DD_OK
}
~unimpl DuplicateSurface(_surface: *mut IDirectDrawSurface7, _out: *mut *mut IDirectDrawSurface7) {
debug!("DuplicateSurface");
}
~unimpl EnumDisplayModes(
flags: u32,
_desc: *const DDSURFACEDESC2,
_param: *mut c_void,
_callback: LPDDENUMMODESCALL... | Rust | 0 |
["progress"]
self.goal: int = current["goal"]
self.started_at: datetime.datetime = parse_timestamp(current["started_at"])
self.expires_at: datetime.datetime = parse_timestamp(current["expires_at"])
self.type: Literal["treasure", "golden_kappa", "regular"] = current["type"]
self.t... | Python | 1 |
pub type __int_least16_t = __int16_t;
pub type __uint_least16_t = __uint16_t;
pub type __int_least32_t = __int32_t;
pub type __uint_least32_t = __uint32_t;
pub type __int_least64_t = __int64_t;
pub type __uint_least64_t = __uint64_t;
pub type __quad_t = ::ctypes::c_long;
pub type __u_quad_t = ::ctypes::c_ulong;
pub typ... | Rust | 0 |
name} ({uploaded_file.size} bytes)")
# Process the file
result = process_uploaded_file(uploaded_file, model_option)
if result is not None:
processed_image, detection_results = result
# Store in session state
st.session_state.proc... | Python | 1 |
from collections import defaultdict
class Solution:
def validSubstringCount(self, word1: str, word2: str) -> int:
'''只要指定的字母出现了,就算有多个有多余的字符也满足条件的类型的题目。使用两个字典对比,第一个为条件字典condict,第二个为当前字典currendict。
以条件字典的长度n表示存在n个不同的字符。当两个字典的某个字符相等时。n减1.一直向右扩展,直到满足n==0,满足n后不断,收缩左边,直到不满足n==0
然后通过累加left的值即可得到总... | Python | 1 |
pend(lifetime_output[2])
Mean .append(lifetime_output[3])
except:
pass
fit_info = {"ActiveBins": ActiveBins, "Lifetimes":Lifetimes, "x0":x0, "FWHM":FWHM, "Mean":Mean}
fit_info = pd.DataFrame(fit_info)
return fit_info
def statistical_lifetime(lifetimes, bins, s... | Python | 1 |
lin
elif "Blue-Striped" in unparsed_name:
variation_name = "Basculin Blue-Striped"
elif "White-Striped" in unparsed_name:
variation_name = "Basculin White-Striped"
elif "Red-Striped" in unparsed_name:
variation_name = "Basculin Red-Striped"
# Case for alternate form: Tauros
... | Python | 1 |
`ARPHRD_ETHER` ([`LinkLayerType::Ether`](enum.LinkLayerType.html))
/// - the linx index defaults to 0
/// - the flags default to 0 ([`LinkFlags::new()`](struct.LinkFlags.html#method.new))
/// - the change master default to 0 ([`LinkFlags::new()`](struct.LinkFlags.html#method.new))
pub fn new() -> Self ... | Rust | 0 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# 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 o... | Python | 1 |
import pytest
glbX = 100
# @pytest.mark.num
def test_greater():
n = 10
assert n < glbX
# @pytest.mark.num
def test_equal():
n = 100
assert n >= glbX
# @pytest.mark.num
def test_less():
n = 500
assert n < glbX
# @pytest.mark.text
def test_equal_ascii():
assert "a" == "a"
# @pytest.mark.t... | Python | 1 |
# config.py
"""
Módulo de configuración para el simulador de logs.
Contiene constantes globales como las rutas de los archivos de log.
"""
# Diccionario que mapea las tecnologías con sus archivos de logs
LOG_FILES = {
"Cisco": "logs/cisco_logs.txt",
"Fortinet": "logs/fortinet_logs.txt",
"Huawei": "logs/hu... | Python | 1 |
{
labels: labs2,
has_jump: false, value: AgreeExpr::Unset,
ret: tgt, dcs: vec![]
};
assert!(self.labels.insert(v, data).is_none());
UnelabStmt::Label(v, todo.into())
}
}
}
fn finish_stmt(&mut self,
hir::Spanned {span, k: stmt}: hir::Spanned<'a, Un... | Rust | 0 |
").join("template.toml").exists());
assert!(dir.path().join("some-project").join("logo.png").exists());
}
#[test]
fn can_generate_from_local_path_with_directory() {
let dir = tempdir().unwrap();
let tpl = Template::from_input("examples/with-directory", None).unwrap();
let re... | Rust | 0 |
# 4. Forward pass
with torch.no_grad():
logits = model.forward_with_cand_embeddings(
clicked_ids, clicked_mask, candidate_emb.unsqueeze(0)) # (1, K)
scores = logits.squeeze(0) # (K,)
topk_vals, topk_idxs = torch.topk(scores, k=min(topk, scores.size(0)))
return scores, topk_i... | Python | 1 |
use morgan_interface::signature::{Keypair, KeypairUtil, Signature};
use std::collections::HashMap;
use std::sync::Arc;
const DROPS_IN_SEGMENT: u64 = SLOTS_PER_SEGMENT * DEFAULT_DROPS_PER_SLOT;
fn test_instruction(
ix: &OpCode,
program_accounts: &mut [Account],
drop_height: ... | Rust | 0 |
);
}
#[test]
fn no_const_assign_invalid() {
assert_lint_err::<NoConstAssign>("const x = 0; x = 1;", 13);
assert_lint_err::<NoConstAssign>("const {a: x} = {a: 0}; x = 1;", 23);
assert_lint_err::<NoConstAssign>("const x = 0; ({x} = {x: 1});", 15);
assert_lint_err::<NoConstAssign>("const x = 0;... | Rust | 0 |
wdsourcingLayer(self.config)
def forward(self, x, adj):
output, h = self.base_model(x, adj)
h = self.cl(output)
out = F.softmax(h, dim=2)
return out, h, output
class CrowdsourcingLayer(torch.nn.Module):
def __init__(self, config):
super(CrowdsourcingLayer, self).__ini... | Python | 1 |
self._next_token()
ast = StatementsNode()
# Парсинг блоков, до основного кода программы.
while not self._match(TokenTypes.BEGIN):
self._require(TokenTypes.PROGRAM, TokenTypes.VAR)
if self._current_token.token_type == TokenTypes.PROGRAM:
... | Python | 1 |
f1_score(y_test, y_pred, average="weighted", zero_division=0),
}
pd.DataFrame([metrics]).to_csv(OUT_DIR / "knn_tsla_metrics.csv", index=False)
cm = confusion_matrix(y_test, y_pred)
pd.DataFrame(cm, index=["Real: 0", "Real: 1"], columns=["Pred: 0", "Pred: 1"]).to_csv(
OUT_DIR / "knn_tsla_confusion_matrix.csv", ind... | Python | 1 |
that is witnessed in this helper.
///
/// `strict` = true constrains the final running sum to be zero, i.e.
/// constrains alpha to be within WINDOW_NUM_BITS * num_windows bits.
pub fn witness_decompose(
&self,
region: &mut Region<'_, F>,
offset: usize,
alpha: Option<F>,... | Rust | 0 |
e https://github.com/rraval/git-nomad/issues/2
#[test]
fn issue_2_all() {
let origin = GitRemote::init();
let host0 = origin.clone("user0", "host0");
sync_host(&host0);
let host1 = origin.clone("user0", "host1");
sync_host(&host1);
// both hosts have synced, th... | Rust | 0 |
ime(2000, 1, 1)
fig, ax = plt.subplots()
arrow = FancyArrowPatch((0, dtime), (0.01, dtime))
ax.add_patch(arrow)
@image_comparison(["large_arc.svg"], style="mpl20")
def test_large_arc():
fig, (ax1, ax2) = plt.subplots(1, 2)
x = 210
y = -2115
diameter = 4261
for ax in [ax1, ax2]:
... | Python | 1 |
::Pong = self {
true
} else {
false
}
}
/// Is this opcode reserved?
pub fn is_reserved(self) -> bool {
match self {
OpCode::Reserved3
| OpCode::Reserved4
| OpCode::Reserved5
| OpCode::Reserved6
| Op... | Rust | 0 |
alsey",
"Hammer",
"Happy",
"<NAME>",
"Harding",
"Harlequin",
"Harris",
"Harrison",
"<NAME>",
"<NAME>",
"Heart",
"Heatwave",
"Heaven",
"Hedtke",
"Helium",
"Hell",
"Henbane",
"Hercules",
"Hermit",
"Heroin",
"Hexnut",
"Hiho",
"Hill",
... | Rust | 0 |
对数域微调:上下调更平滑,再做 EMA 平滑与边界裁剪
"""
import math
import torch
# —— 保护性默认值(若没设定)——
if not hasattr(self, "lambda_ewc"):
self.lambda_ewc = float(getattr(self.hparams, "lambda_ewc", 1.0))
if not hasattr(self, "_drift_values"):
self._drift_values = []
... | Python | 1 |
from charset_normalizer import from_bytes
import pytest
import platform
@pytest.mark.xfail(platform.python_version_tuple()[0] == "3" and platform.python_version_tuple()[1] == "7", reason="Unicode database is too old for this case (Python 3.7)")
def test_unicode_edge_case():
payload = b'\xef\xbb\xbf\xf0\x9f\xa9\xb3... | Python | 1 |
tion(z, 1, 4)
assert np.allclose(shifts, shifts_expected, atol=0.2)
@pytest.mark.skip(reason="FAO: M.Nord, skipping to get green for new code")
@pytest.mark.parametrize("shifts_expected", [(+0.5, -3.5)])
@pytest.mark.parametrize("sigma", [1, 2, 3])
def test_single_pixel_spot(self, shifts_expect... | Python | 1 |
import pytest
import rclpy
from std_msgs.msg import Int64
from core.a_node import is_prime, calculate_n_primes, ANode
@pytest.fixture
def rclpy_setup_teardown():
rclpy.init()
yield
rclpy.shutdown()
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) ==... | Python | 1 |
def parse_only_numbers(text: str) -> int:
ret = 0
for ch in text:
if ch.isdigit():
ret = ret * 10 + int(ch)
return ret | Python | 1 |
.to_str()
.map(|prune_w| prune_w.parse::<f32>().unwrap())
.unwrap(),
prune_h_str
.to_str()
.map(|prune_h| prune_h.parse::<f32>().unwrap())
.unwrap(),
... | Rust | 0 |
'c' => Some(LaneType::Construction),
_ => None,
}
}
}
<filename>frontend/src/agents/auth.rs<gh_stars>10-100
// https://github.com/yewstack/yew/tree/master/examples/pub_sub/src
use crate::model::Auth;
use serde::{Deserialize, Serialize};
use serde_json;
use std::collections::HashSet;
use ye... | Rust | 0 |
json::<spreadsheets_batch_update::BatchUpdateResponse>()?)
}
// https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet
// GET https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values:batchGet
pub fn get_batch_values<S: AsRef<str>>(
&self,
tok... | Rust | 0 |
o_list_t>(),
24usize,
concat!("Size of: ", stringify!(sigar_who_list_t))
);
assert_eq!(
::std::mem::align_of::<sigar_who_list_t>(),
8usize,
concat!("Alignment of ", stringify!(sigar_who_list_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<sigar_who_list... | Rust | 0 |
e_as_register_token:
# Step 1: Zero out masks for same frame interactions
same_frame = torch.eye(T, device=device, dtype=mask.dtype).view(1, T, T, 1, 1).repeat(mask.shape[0], 1, 1, H * W, H * W)
mask = torch.where(same_frame, same_frame, mask)
return rearrange(mask, "B T1 T2... | Python | 1 |
_with_carbon_metadata(carbon_metadata6).inner.is_valid(DEFAULT_DAY_DURATION));
// }
// #[test]
// fn bond_with_carbon_is_not_valid() {
// let carbon_metadata1 = crate::bond::CarbonUnitsMetadata{
// count: 100_000,
// carbon_distribution: crate::bond::CarbonDistribution{
// investors: 10... | Rust | 0 |
buf2310, (int*) buf2311, (int*) buf2312);
#endif
#ifndef __LP64__
rsgMeasureText(*(rs_allocation*)buf2313, (int*) buf2314, (int*) buf2315, (int*) buf2316, (int*) buf2317);
#endif
#ifndef __LP64__
rsgMeshComputeBoundingBox(*(rs_mesh*)buf2318, (float*) buf2319, (float*) buf2320, (float*) buf2321, (float*) buf232... | Rust | 0 |
String
}
}
impl ResourceQuery for KeyPairQuery {
type Item = KeyPair;
const DEFAULT_LIMIT: usize = 50;
fn can_paginate(&self) -> Result<bool> {
if self.can_paginate {
api::supports_keypair_pagination(&self.session)
} else {
Ok(false)
}
}
fn ext... | Rust | 0 |
1.cos() * theta2.cos() * (delta_lambda / 2.0).sin().powi(2);
let c = 2.0 * a.sqrt().asin();
(EARTH_RADIUS * c).round() as u32
}
pub fn load_from_pbf(pbf: impl Read + Seek) -> Result<(Vec<Node>, Vec<Edge>), Box<dyn Error>> {
let mut pbf_reader = OsmPbfReader::new(pbf);
let mut ways = Vec::new();
fo... | Rust | 0 |
def solve(grid):
H, W = len(grid), len(grid[0])
sepR = [r for r in range(H) if all(grid[r][c] == 4 for c in range(W))]
sepC = [c for c in range(W) if all(grid[r][c] == 4 for r in range(H))]
def intervals(seps, N):
iv, s = [], 0
for x in seps + [N]:
if s < x:
i... | Python | 1 |
import moderngl
import numpy
from PIL import Image
from .enums import CONVERSION, SAMPLING
from pathlib import Path
def load_shader(shader):
path = Path(__file__).resolve().parent / "shaders" / shader
return path.read_text()
def render(image: Image.Image, conversion: CONVERSION, sampling: SAMPLING):
# Sha... | Python | 1 |
en(args.gen_wavdir_or_wavscp) as f:
gen_files = [line.strip().split(None, 1)[1] for line in f.readlines()]
if gen_files[0].endswith("|"):
raise ValueError("Not supported wav.scp format.")
# Get and divide list
if len(gen_files) == 0:
raise FileNotFoundError("Not found an... | Python | 1 |
api_rsp: Response = rsp.json()?;
println!("{:#?}", api_rsp);
Ok(())
}
<reponame>toisme/mirakc
use actix::prelude::*;
use chrono::{DateTime, Duration};
use log;
use serde::Deserialize;
use serde_json;
use tokio::prelude::*;
use tokio::io::BufReader;
use crate::command_util;
use crate::datetime_ext::*;
use cra... | Rust | 0 |
mut i32,
) -> Result<()> {
ok_or_oci_err!(|err|
OCIIntervalCompare(hndl, err, inter1, inter2, result)
)
}
pub(crate) fn interval_divide(
hndl: *const c_void,
err: &OCIError,
dividend: &OCIInterval,
divisor: &OCINumber,
result: &mut OCIInterval,
) -> Result<()> ... | Rust | 0 |
# test_large_upload.py
import os
import tempfile
from s3sim.s3_operations import (
create_bucket,
upload_large_file,
list_files,
delete_bucket
)
# Set endpoint for Moto server
os.environ['S3_ENDPOINT_URL'] = 'http://localhost:5000'
# Create a temporary large file (~15 MB for testing)
temp_dir = tempfi... | Python | 1 |
x0] = 3;
cpu.v[0xC] = 0xF;
cpu.v[0xD] = 0xA;
cpu.skp(0x0); // Key directed to by register V0 has been pressed
assert!(cpu.pc == 0x2);
cpu.skp(0xC); // Key directed to by register VC has bot been pressed
assert!(cpu.pc == 0x2);
cpu.skp(0xD); // Key directed to by register VD has been pressed
assert!(cpu.pc ==... | Rust | 0 |
#!/usr/bin/env python3
"""
Example of using the CheckpointManager for fixed checkpoint files
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from src.isc_ai.core import ISCCore
from src.isc_ai.trainer_utils import CheckpointManager
import matplotlib.pyplot as plt
import nump... | Python | 1 |
import sys
R, C, N = map(int, input().split())
grid = [list(input().strip()) for _ in range(R)]
times = [[-1] * C for _ in range(R)]
for i in range(R):
for j in range(C):
if grid[i][j] == 'O':
times[i][j] = 0
for t in range(1, N + 1):
if t % 2 == 0 and t >= 2:
for i in range(R):
... | Python | 1 |
C: GenericConfig<D, F = F>,
S: Stark<F, D>,
{
let permutation_pairs = stark.permutation_pairs();
let permutation_batches = get_permutation_batches(
&permutation_pairs,
permutation_challenge_sets,
config.num_challenges,
stark.permutation_batch_size(),
);
permutati... | Rust | 0 |
eature = "Win32_Foundation")]
pub fn GetSystemDpiForProcess(hprocess: super::super::Foundation::HANDLE) -> u32;
#[doc = "*Required features: 'Win32_UI_HiDpi'*"]
pub fn GetSystemMetricsForDpi(nindex: i32, dpi: u32) -> i32;
#[doc = "*Required features: 'Win32_UI_HiDpi'*"]
pub fn GetThreadDpiAwarenessC... | Rust | 0 |
"""QUESTÃO 2 - Escreva um aplicativo que solicita ao usuário que insira o tamanho do lado de um quadrado e, então, exibe um quadrado vazio
desse tamanho com asteriscos. Seu programa deve trabalhar com quadrados de todos os comprimentos de lado possíveis entre 1 e 20."""
lado = int(input("Digite o lado do quadrado: "... | Python | 1 |
"""
Test script for the advanced 3-item bundle generation API
"""
import requests
import json
import numpy as np
def test_advanced_bundle_api():
"""Test the advanced bundle generation API with various scenarios"""
url = "http://localhost:5001/generate_advanced_bundle"
# Test Case 1: Basic request with... | Python | 1 |
constraint.push((v, -1.0));
force_x_neg_constraint.push((desire_var, desire.x as f64));
problem.add_constraint(&force_x_pos_constraint, ComparisonOp::Le, 0.0);
problem.add_constraint(&force_x_neg_constraint, ComparisonOp::Le, 0.0);
force_y_pos_constraint.push((w, -1.0));
force_y_pos_constraint.push(... | Rust | 0 |
from fastapi import HTTPException, status
from src.app.role.domain.entity.role_entity import RoleEntity
from src.app.role.infrastructure.model.role_model import RoleModel
from src.app.role.domain.interface.role_repository import RoleRepository
from src.app.base.application.usecase.base_usecase import BaseUseCase
clas... | Python | 1 |
ilters.sample`.
# Importantly, the cell connectivity enables direct interpolation
# inside the domain without needing distance or weighting parametization.
#
# First, show that sample does not work with point clouds with data.
# Either :func:`pyvista.DataSetFilters.interpolate` or the
# ``snap_to_closest_point`` parame... | Python | 1 |
let arc_store = Arc::new(store);
let adapter = Arc::new(NoopAdapter {});
for n in 1..4 {
let mut b = core::Block::new(&prev.header, vec![], reward_key).unwrap();
b.header.timestamp = prev.header.timestamp + time::Duration::seconds(60);
let (difficulty, _) = consensus::next_target(b.header.timestamp.to_timespe... | Rust | 0 |
bound.
WeightedRandom,
}
impl Default for NewNodeOrder {
fn default() -> Self {
NewNodeOrder::WeightedRandom
}
}
/// An enum listing the Group of choices we can make
/// For example, we can make first all DimKind decisions, then all Order decisions, etc.
#[derive(Clone, Serialize, Deserialize, De... | Rust | 0 |
urn model_name + ext
def get_remove_epoch_no(args: argparse.Namespace, epoch_no: int):
if args.save_last_n_epochs is None:
return None
remove_epoch_no = epoch_no - args.save_every_n_epochs * args.save_last_n_epochs
if remove_epoch_no < 0:
return None
return remove_epoch_no
def get_r... | Python | 1 |
sampling_metadata.repetition_penalties)
assert torch.allclose(expected_sampling_metadata.prompt_token_ids,
sampling_metadata.prompt_token_ids)
assert (expected_sampling_metadata.output_token_ids ==
sampling_metadata.output_token_ids)
assert (
expe... | Python | 1 |
return
if not download_file(tg, m, "temp_auto_delivery.cfg"):
return
bot.send_message(m.chat.id, "🔁 Проверяю валидность файла...")
try:
new_config = cfg_loader.load_auto_delivery_config("storage/cache/temp_auto_delivery.cfg")
except excs.ConfigParseError as e:... | Python | 1 |
"""
In this program we would use the Caesar Cipher technique to
encrypt and decrypt our message
Done By Adeeb Imam
Date 28th May 2024
"""
def caesar(text, shift, cryptograph):
cipher_text = ""
for letter in text:
if letter in alphabet:
position = alphabet.index(letter)
if cryp... | Python | 1 |
&& nextch(rdr) == '/' {
bump(rdr);
bump(rdr);
curr_line += ~"/";
level -= 1;
} else { bump(rdr); }
}
}
}
if str::len(curr_line) != 0 {
trim_whitesp... | Rust | 0 |
device"]
pub const SND_CTL_ELEM_IFACE_HWDEP: _snd_ctl_elem_iface = 1;
#[doc = " Mixer"]
pub const SND_CTL_ELEM_IFACE_MIXER: _snd_ctl_elem_iface = 2;
#[doc = " PCM"]
pub const SND_CTL_ELEM_IFACE_PCM: _snd_ctl_elem_iface = 3;
#[doc = " RawMidi"]
pub const SND_CTL_ELEM_IFACE_RAWMIDI: _snd_ctl_elem_iface = 4;
#[doc = " Ti... | Rust | 0 |
# routes.py
from flask import Blueprint, render_template, request, jsonify, current_app
from app.forms import TechStackForm
from app.ai_logic.stack_analyzer import analyze_stack
from app.ai_logic.recommendation_engine import get_recommendations
from app.models import TechStack
main = Blueprint("main", __name__)
@ma... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class CalendarBookingLine(models.Model):
_name = 'calendar.booking.line'
_description = "Meeting User/Resource Booking"
_order = "create_date DESC, id DESC"
_rec_name = "... | Python | 1 |
f.slots_per_restore_point != on_disk_config.slots_per_restore_point {
return Err(StoreConfigError::MismatchedSlotsPerRestorePoint {
config: self.slots_per_restore_point,
on_disk: on_disk_config.slots_per_restore_point,
});
}
Ok(())
}
}
impl St... | Rust | 0 |
urn "has stress"
elif answer == "no":
return "no stress"
else:
return "other"
logger.warning(f"Could not extract label from text: {text}")
return "other"
@extract_label_register.register("election")
def election_extract_label(text):
logger = LoggerCon... | Python | 1 |
self.download_mods(download_urls, update)
self.write_mmc_files()
self.make_zip()
clear()
showinfo(
self.factory.language.translate('download.finish.title'),
self.factory.language.translate('download.fi... | Python | 1 |
);
t
}
};
let mut blueprint = Blueprint::new();
for (k, v) in deps {
if let Value::Table(mut map) = v {
let stage = if let Some(value) = map.remove("stage") {
value
.as_integer()
... | Rust | 0 |
/// over tcp to server at multiaddr `server_addr`.
fn bench_tcp_muxer_send(b: &mut Bencher, msg_len: &usize, server_addr: Multiaddr) {
let mut runtime = Runtime::new().unwrap();
let client_transport = build_tcp_muxer_transport();
// Benchmark sending some data to the server.
let (_client_muxer, _clien... | Rust | 0 |
{
assert_div_rem_equivalence(divisor, numerator);
}
#[test]
fn generated_numerators_with_edge_case_divisors_are_div_rem_equivalent(
divisor in select(vec![1 as $primitive_type, 2 as $primitive_type, core::$primitive_type::MAX ... | Rust | 0 |
),返回信息
:type TxnReturnMsg: str
:param _CnsmrSeqNo: String(22),交易流水号
:type CnsmrSeqNo: str
:param _RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self._FrontSeqNo = None
self._ReservedMsg = None
self._TxnReturnCode = ... | Python | 1 |
#String creation
name="oh god beautiful"
line="This is the nature of beautiful"
#multiline
quote="""Oh dare devil"""
#length
print(len(name))
#index
print(name[3])
#slicing
print(name[0:7])
#negative index
print(quote[-1])
#loop
for char in line:
print(char,end="")
#concatenation
quotes=(name+"life")
print("\n",quo... | Python | 1 |
"r1bqkbnr/pp1npppp/3p4/1Bp5/4P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 2 4",
"h1f1",
"r1bqkbnr/pp1npppp/3p4/1Bp5/4P3/5N2/PPPP1PPP/RNBQKR2 b Qkq - 3 4",
)?;
// The kingside rook is captured; the king can no longer castle king side.
assert_make_move(
"rnbqkb1r/pppppppp/... | Rust | 0 |
--- scripts/ldmap.py.orig 2021-01-23 17:32:15 UTC
+++ scripts/ldmap.py
@@ -29,10 +29,10 @@ class MapMaker:
coordinates of the haplotype marker genomic positions.
'''
def __init__(self, markerFilename, haplotypesFilename):
- print "reading haplotype base coordinates ...."
+ print("reading ha... | Python | 1 |
# """
# 处理角色关系变化
# Keyword argumenys:
# character_id -- 状态变化数据所属角色id
# change_data -- 状态变化数据
# """
# character_data: game_type.Character = cache.character_data[character_id]
# for now_character in change_data.target_change:
# change_character_social_now(character_id, now_charact... | Python | 1 |
> {
type Response = super::HealthCheckReply;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::HealthCheckRequest>,
... | Rust | 0 |
sk);
}
pub fn fetch(&mut self) -> Option<Arc<TaskControlBlock>> {
self.ready_queue.pop_front()
}
pub fn find_task(&self, pid: usize) -> Option<Arc<TaskControlBlock>> {
for task in self.ready_queue.iter() {
if task.pid.0 == pid {
return Some(Arc::clone(task))... | Rust | 0 |
import os
import json
from tqdm import tqdm
import time
data = []
with open("./data.json", "r") as f:
for line in f:
data.append(eval(line))
print(data)
# model = 'gpt-4-turbo'
# model = 'gpt-4o-2024-05-13'
model = 'gpt-3.5-turbo-0125'
# model = 'baseline'
# model = 'gpt-3.5-turbo-0125-autoagent'
# model... | Python | 1 |
yhow::Result<Vec<ItemWithPrice>> {
let items = self.search(query)?;
let item_prices = &self.prices.load()?.data;
// Join price data in for each item
let items_with_prices = items
.into_iter()
.map(|item| {
let price = item_prices.get(&item.id).copi... | Rust | 0 |
from copy import copy
from app.lib.tags_format import tags_format
from app.models.db.element import Element
from app.models.tags_format import TagFormat
def tags_diff_mode(previous_element: Element | None, elements_data: list[dict]) -> None:
"""Update tags data to include necessary tags diff mode information."""... | Python | 1 |
::new(Key::Char('c'), KeyPress::CTRL)),
0x04 => Some(KeyPress::new(Key::Char('d'), KeyPress::CTRL)),
0x05 => Some(KeyPress::new(Key::Char('e'), KeyPress::CTRL)),
0x06 => Some(KeyPress::new(Key::Char('f'), KeyPress::CTRL)),
0x07 => Some(KeyP... | Rust | 0 |
alor en vivo de Bitcoin.",
'buy_or_run_program': "\nIntroduce el número del programa que quieres comprar o ejecutar (o 'salir'): ",
'purchase_successful_program': "¡Compra exitosa! Ahora puedes usar el programa '{}'.",
'not_enough_tc_program': "No tienes suficientes TerminalCoins para comprar es... | Python | 1 |
'''
❓ First, what is the Two Sum problem?
Can you try to explain what the Two Sum problem is in your own words?
If you’re not sure yet, I’ll guide you:
You are given:
• An array of integers: nums
• A target value: target
The task is to find two distinct indices i and j such that:
\text{nums}[i] + \text{nums}[j] ... | Python | 1 |
= 32
default_config.method.chunk_size = 8
default_config.train.group_name = default_config.model.model_path
else:
raise ValueError(f"Config {config_name} does not exist."
"Please append this config into the file before calling it")
def get_toxicity_score(scores):
"Extract value ... | Python | 1 |
.
///
/// * If `true`, the auditor authority must approve newly configured accounts (see
/// `ConfidentialTransferInstruction::ConfigureAccount`)
/// * If `false`, no approval is required and new accounts may be used immediately
pub approve_new_accounts: PodBool,
/// * If non-zero,... | Rust | 0 |
# fmt: on
self.assertTrue(np.allclose(generated_ids, EXPECTED_LOGITS))
# fmt: off
EXPECTED_TRANSCRIPT = [
" Mr. Quilter is the apostle of the middle classes, and we are glad to",
" Nor is Mr. Quilter's manner less interesting than his matter.",
" He... | Python | 1 |
"""
Off-chain code of taker and giver in fortytwo.
"""
import os
import cbor2
from blockfrost import ApiUrls
from retry import retry
from pycardano import *
NETWORK = Network.TESTNET
def get_env_val(key):
val = os.environ.get(key)
if not val:
raise Exception(f"Environment variable {key} is not s... | Python | 1 |
=
rflags::RFlags::FLAGS_IOPL3 | rflags::RFlags::FLAGS_A1 | rflags::RFlags::FLAGS_IF;
// Switch to user-space with initial zeroed registers.
//
// Stack is set to the initial stack for the process that
// was allocated by the kernel.
//
// `sysretq` expectatio... | Rust | 0 |
React.createClass({
displayName: "bar"
}));
"#
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| tr(),
object_property,
r#"
({
foo: createReactClass({})
});
({
bar: React.createClass({})
});
"#,
r#"
({
foo: createReactClass({
displayName: "foo"
})
});
({
bar: React... | Rust | 0 |
ll[self.fidx[0]],
'f-score-10': F[self.fidx[0]], # threshold = 1.0%
'f-score-15': F[self.fidx[1]], # threshold = 1.5%
'f-score-20': F[self.fidx[2]], # threshold = 2.0%
}
if onet_samples is not None:
if len(mesh.triangles) == 0:
out_dict... | Python | 1 |
import numpy as np
def parse_file(file_path):
with open(file_path, 'r') as file:
n = int(file.readline().strip())
arrays = []
for _ in range(n):
line = file.readline().strip()
array = list(map(int, line.split()))
arrays.append(array)
... | Python | 1 |
self.assertEqual(ingrediente['nombre'], ingrediente_creado.nombre)
self.assertEqual(ingrediente['unidad'], ingrediente_creado.unidad)
self.assertEqual(float(ingrediente['costo']), float(ingrediente_creado.costo))
self.assertEqual(float(ingrediente['calori... | Python | 1 |
self.db.expect("db is not initialized").commit().await
}
#[cfg(feature = "reldb")]
pub async fn rollback(self) -> TardisResult<()> {
self.db.expect("db is not initialized").rollback().await
}
#[cfg(feature = "cache")]
pub fn cache(&self) -> &'static TardisCacheClient {
Tardi... | Rust | 0 |
lst=list(input())
a,b=map(str,input().split())
ai=0
bi=0
for i in range(len(lst)):
if lst[i] == a:
ai=i
if lst[i] == b:
bi=i
for i in range(-1,2,2):
ani = ai+i
bni = bi+i
if ani>=0 and ani<len(lst):
lst[ani] = '#'
if bni >= 0 and bni < len(lst):
lst[bni] = '#'
f... | Python | 1 |
aracters}]+", name):
message = ", ".join(f"'{c}'" for c in special_characters)
frappe.throw(
_("Name cannot contain special characters like {0}").format(message), frappe.NameError
)
return name
def append_number_if_name_exists(doctype, value, fieldname="name", separator="-", filters=None):
if not filters:... | Python | 1 |
'','')
encryptedSessionKey = ntlm.generateEncryptedSessionKey(keyExchangeKey,randomSessionKey)
hexdump(encryptedSessionKey)
print "\n"
print "AUTHENTICATE MESSAGE"
encryptedSessionKey = ntlm.generateEncryptedSessionKey(keyExchangeKey,randomSessionKey)
ntlmChallengeResponse = ntlm.NTLMAuthChallengeResponse(user, passwo... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.