text string | label_name string | labels int64 |
|---|---|---|
"status"] if x["name"] == result)
x["value"] = False
self.expected_result["valid"] = False
def test_host_no_problems(self):
self.expected_result["profiles"]["test_profile"] = []
self._test_host_contact()
def test_unresolvable_server_name(self):
self._inject_failure... | Python | 1 |
{msg:"Unable to find user."}
}
},
Err(e) => {
error!("{}", e);
ApiResult::Failure{msg:"Failed to find user. Invalid ID."}
}
}
},
Err(e) => {
... | Rust | 0 |
-> io::Result<()> {
/// let responder = Responder::new()?;
/// // bind service
/// let _http_svc = responder.register(
/// "_http._tcp".into(),
/// "my http server".into(),
/// 80,
/// &["path=/"]
/// );
/// # Ok(())
/// # }
/// ```
... | Rust | 0 |
},
Event::KeyDown { keycode: Some(Keycode::F), .. } => { chip8.keypad[0xE] = 1; debounce[0xE] = DEBOUNCE_DELAY; },
Event::KeyDown { keycode: Some(Keycode::Z), .. } => { chip8.keypad[0xA] = 1; debounce[0xA] = DEBOUNCE_DELAY; },
Event::KeyDown { keycode: Some(Keycode::X), ... | Rust | 0 |
"""
Tests for the parts of jsonschema related to the :kw:`format` keyword.
"""
from unittest import TestCase
from jsonschema import FormatChecker, ValidationError
from jsonschema.exceptions import FormatError
from jsonschema.validators import Draft4Validator
BOOM = ValueError("Boom!")
BANG = ZeroDivisionError("Bang!... | Python | 1 |
"""Custom exceptions for Secret's Garden."""
from typing import Union
class SecretsGardenError(Exception):
"""Base exception class for all Secret's Garden errors."""
def __init__(self, message: str, details: Union[str, None] = None) -> None:
super().__init__(message)
self.message = message
... | Python | 1 |
is_zero()
}
let cf = self.regs.n.configuration();
let save_q = nonzero(cf & 0b01000_u8);
let savep_e = nonzero(cf & 0b00100_u8);
let savep_ix = nonzero(cf & 0b00010_u8);
let indexed = nonzero(cf & 0b00001_u8);
let j = self.regs.n.index_address();
let left:... | Rust | 0 |
O error: {:?}", err),
}
}
}
<reponame>hnakamur/sled
//! # Working with `Log`
//!
//! ```
//! let config = pagecache::ConfigBuilder::new()
//! .temporary(true)
//! .segment_mode(pagecache::SegmentMode::Linear)
//! .build();
//! let log = pagecache::Log::start_raw_log(config).unwrap();
//! let (fi... | Rust | 0 |
pub lp_shares_withdrawn: Uint128,
/// True if MARS--UST LP Shares are currently staked with the MARS LP Staking contract
pub are_staked_for_single_incentives: bool,
/// True if MARS--UST LP Shares are currently staked with Astroport Generator for dual staking incentives
pub are_staked_for_dual_incen... | Rust | 0 |
import pandas as pd
import math
import os
# Haversine formula to calculate distance between two coordinates
def haversine(lat1, lon1, lat2, lon2):
R = 6371 # Earth radius in kilometers
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = math.sin(dlat / 2)**2 + math.cos(math.radians... | Python | 1 |
x7A, 0x2F, 0xFF, 0xD1, 0xE9, 0x71, 0xFC, 0x3E,
]
);
set_trainer_pic_test!(
set_trainer_pic_16,
16,
"../secrets/data/trainer_pic/16.png",
PicEncodingMethod::TWO(1),
0x4D24F,
vec![
0x77, 0xBB, 0x5A, 0x55, 0x3D, 0x14, 0x8E, 0xA9, 0x3C, 0x95, 0x17, 0xA9, 0x08, 0x21, 0x93,
0xC5, 0... | Rust | 0 |
ient_lux: 30., display_nits: 8.7 });
lux_to_nits.push(BrightnessPoint { ambient_lux: 60., display_nits: 18.27 });
lux_to_nits.push(BrightnessPoint { ambient_lux: 100., display_nits: 32.785 });
lux_to_nits.push(BrightnessPoint { ambient_lux: 150., display_nits: 36.82 });
lux_to_nits.push(... | Rust | 0 |
url": "https://api.github.com/users/Codertocat/following{/other_user}",
"gists_url": "https://api.github.com/users/Codertocat/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Codertocat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Codertocat/subscriptions",
"... | Rust | 0 |
#!/usr/bin/env python3
import sys
import json
import r2pipe
import binascii
def main():
movs = []
r2 = r2pipe.open(sys.argv[1], flags=['-2'])
r2.cmd("aaaa")
functions = json.loads(r2.cmd("aflj"))
'''Loop over all analyzed functions.'''
for f in functions:
r2.cmd("s %s" % f['offset'])
... | Python | 1 |
, Method::Centroid);
dend_prim.eq_with_epsilon(&dend_generic, 0.0000000001)
}
fn prop_generic_median_primitive(mat: DistinctMatrix) -> bool {
let dend_prim = primitive(
&mut mat.matrix(), mat.len(), Method::Median);
let dend_generic = generic(
... | Rust | 0 |
import torch
def broyden(g, x_init, J_inv_init, max_steps=50, cvg_thresh=1e-5, dvg_thresh=1, eps=1e-6):
"""Find roots of the given function g(x) = 0.
This function is impleneted based on https://github.com/locuslab/deq.
Tensor shape abbreviation:
N: number of points
D: space dimension
... | Python | 1 |
import pytest
from polog.handlers.file.locks.abstract_single_lock import AbstractSingleLock
class LittleLessAbstractLock(AbstractSingleLock):
def __init__(self, on):
if not on:
self.off()
def test_off_lock_is_working():
"""
Проверяем, что метод .off() - работает.
Его задача - пер... | Python | 1 |
# The MIT License (MIT).
#
# Copyright (c) 2024-2025 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru>
#
# 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 limit... | Python | 1 |
Call(Ident("Log"), [StringLit(String, "default")])] }))"#
);
}
#[test]
fn parse_with_comment() {
let stmt = lang::stmt(
r#"
/* this is a multiline comment
blah blah blah
*/
Int32 a = /* stuff */ 2;"#,
)
.unwrap()... | Rust | 0 |
::CrateRoot { definition } => {
let file_id = *definition;
let sf = db.parse(file_id).tree();
InFile::new(file_id.into(), ModuleSource::SourceFile(sf))
}
ModuleOrigin::Inline { definition } => {
InFile::new(definition.file_id, Modul... | Rust | 0 |
Color: u32,
EdgeColor: u32,
VerticalFlag: i32,
String: *const i8,
StringLength: usize,
) -> i32;
pub fn dx_DrawNumberToI(
x: i32,
y: i32,
Num: i32,
RisesNum: i32,
Color: u32,
EdgeColor: u32,
) -> i32;
pub fn dx_Draw... | Rust | 0 |
low=False):
target_pos_1, target_quat_1, gripper_1 = target_ee_states[0]
# target_pos_2, target_quat_2, gripper_2 = target_ee_states[1]
pos_err_1, ori_err_1 = thresholds[0]
pos_err_2, ori_err_2 = thresholds[1]
spend_time = 0
while True:
ee_pos_1, ee_quat_1 = env.get_ee_pose_world()
... | Python | 1 |
add_unary_handler(&METHOD_PD_PUT_CLUSTER_CONFIG, move |ctx, req, resp| {
instance.put_cluster_config(ctx, req, resp)
});
let mut instance = s.clone();
builder = builder.add_unary_handler(&METHOD_PD_SCATTER_REGION, move |ctx, req, resp| {
instance.scatter_region(ctx, req, resp)
});
le... | Rust | 0 |
.0),
City::new(9494, "Syria", "<NAME>", 33.5666667, 36.3666649, 686.0),
City::new(9495, "Syria", "Al Qunaytirah", 33.1252778, 35.8236122, 928.0),
City::new(9496, "Syria", "Tadif", 36.3333333, 37.5333328, 438.0),
City::new(9497, "Syria", "Saraqib", 35.8636111, 36.8005562, 371.0),
City::new(9498, "Syria", "Jayrud", ... | Rust | 0 |
;
((self.bits >> OFFSET) & MASK as u32) != 0
};
SOC_ACTCK_MII_MPHY_ENR { bits }
}
#[doc = "Bit 5"]
#[inline]
pub fn soc_slpck_otg_en(&self) -> SOC_SLPCK_OTG_ENR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bi... | Rust | 0 |
# -*- coding: utf-8 -*-
from .i18n import get_
class MaxDepthInfo:
"""Класс для оформления сведений о страницах с максимальной глубиной вложенности"""
def __init__(self, maxDepthList):
"""
maxDepthList - список кортежей, полученный из класса TreeStat.maxDepth.
Кортежи состоят из двух... | Python | 1 |
get_vocab()
filtered_ids = get_filtered_ids(processor.tokenizer)
vocab_dict = {v: k for k, v in vocab_dict.items()}
if model_args.use_output_embedding_cluster:
output_token_embeddings = encoder.get_output_embeddings().weight[:len(vocab_dict), :]
centroids_dict = {} # 这是用来保存各个centroids... | Python | 1 |
stride=2)
self.layer3 = self._make_layer(block, 64, layers[2], stride=2)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(64 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight... | Python | 1 |
def main():
"""
This program counts down from 10 to 0 and then prints "Liftoff!"
"""
# The loop will iterate from 0 to 9 and print the countdown numbers.
for i in range(10):
# The loop will print the countdown numbers in reverse order.
print(10-i, end=",")
# The loop will pa... | Python | 1 |
true,
(Self::MinusZero, Self::MinusInfinity) => false,
(Self::MinusZero, Self::Nan) => false,
}
}
}
impl PartialOrd for ExtendedBigInt {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match (self, other) {
(Self::BigInt(m), Self::BigInt(n)) => m.p... | Rust | 0 |
:prelude::*;
use molecule_ci_tests::types;
#[test]
fn strict_table() {
let a = types::StrictTableA::default();
let b = types::StrictTableB::default();
let c = types::StrictTableC::default();
assert!(types::StrictTableAReader::verify(a.as_slice()).is_ok());
assert!(types::StrictTableAReader::verif... | Rust | 0 |
{
fn default() -> Struct_sctp_setprim { unsafe { ::std::mem::zeroed() } }
}
/*
* 7.1.11 Set Adaptation Layer Indicator (SCTP_ADAPTATION_LAYER)
*
* Requests that the local endpoint set the specified Adaptation Layer
* Indication parameter for all future INIT and INIT-ACK exchanges.
*/
#[repr(C)]
#[derive(Copy... | Rust | 0 |
::<LittleEndian>()?
);
let parent_reference = Ntfs128Reference(
buffer.read_u128::<LittleEndian>()?
);
let usn = buffer.read_u64::<LittleEndian>()?;
let timestamp = u64_to_datetime(
buffer.read_u64::<LittleEndian>()?
);
let reason = flags:... | Rust | 0 |
from flask import Blueprint, request, jsonify
from .service import save_or_update_social_video, get_all_social_videos
social_video_bp = Blueprint("social_video", __name__)
@social_video_bp.route("/share", methods=["POST"])
def share_video():
data = request.json
video_id = data.get("id")
platform = data.ge... | Python | 1 |
| Y |
/// | default | Argument default value | literal | Y |
/// | default_with | Expression to generate default value | code string | Y |
/// | validator | Input value validator | [`InputValueValidator`](validators/trait.InputValueValidator.... | Rust | 0 |
()?;
let method = strm.read_u8()?.into();
Ok(raw::MethodSelection { ver, method }.into())
}
pub fn read_connect_reply<T: io::Read>(mut strm: T) -> Result<model::ConnectReply, Error> {
trace!("read_connect_reply");
let ver = strm.read_version()?;
let rep = strm.read_rep()... | Rust | 0 |
from aiogram import types
async def set_default_commands(dp):
await dp.bot.set_my_commands(
[
types.BotCommand("start", "Запустить бота"),
types.BotCommand("all", "Смотреть курсы"),
types.BotCommand("items", "Смотреть следующие"),
types.BotCommand("cat", "Вы... | Python | 1 |
imentos específicos AERO]
**Para Franquias:** [Consolidar orientações gerais]
**⚡ Tempo Estimado:** [Indicar tempo para otimizar TMA]
**📋 Categorização:** [Macro/Submotivo para classificação]
### **Informações Adicionais:**
[Qualquer informação técnica relevant... | Python | 1 |
),
reverse=reverse,
)
# Calculate total if we had at least one file.
total_line = ["TOTAL", self.total.n_statements, self.total.n_missing]
if self.branches:
total_line += [self.total.n_branches, self.total.n_partial_branches]
total_line += [self.t... | Python | 1 |
}
fn register_displays(&self, file_name: &str, n: i64) -> Result<()> {
debug!("Registering displays for {}: {}", file_name, n);
let field = self::schema::image_statistics::dsl::total_displays;
self.conn.transaction(|| {
use self::schema::image_statistics::dsl::*;
di... | Rust | 0 |
##########################################################################
#
# Copyright (c) 2011, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... | Python | 1 |
mand::new("LPUSH").arg(&key).args(values);
Ok(self.run_command(command).await?.unwrap_integer())
}
///Push a value to `list` from the right.
///# Return value
///The number of elements in `list`
pub async fn rpush<K, V>(&mut self, list: K, value: V) -> Result<isize>
where
K: As... | Rust | 0 |
rror> {
let class_type = class_type.0;
let class_data = match class_type {
ClassChoice::AegisFighter => &*CLASS_AEGIS,
ClassChoice::BlastArcher => &*CLASS_BLAST,
ClassChoice::SpellCaster => &*CLASS_SPELL,
ClassChoice::TwinStriker => &*CLASS_TWIN,
};
let color = u32::fro... | Rust | 0 |
0, 0), CubeStatus::Active);
grid.update_cube_at_point(&Point(0, 2, 0, 0), CubeStatus::Active);
grid.update_cube_at_point(&Point(1, 2, 0, 0), CubeStatus::Active);
grid.update_cube_at_point(&Point(2, 2, 0, 0), CubeStatus::Active);
assert_eq!(grid.number_of_active_cubes(), 5);
}
#[test]
fn test_grid_tick... | Rust | 0 |
nse: {}", e);
self.handles.stats.send(AddError(Other)).unwrap_or_default();
}
}
});
// await tx tasks
log::trace!("awaiting scan producers");
producers.await;
log::trace!("done awaiting scan producers");
se... | Rust | 0 |
ws::Message::Text(text)) = msg {
let stdin = self.stdin.clone();
let msg = serde_json::from_str::<Value>(&text);
// debug print client messages
println!("\nStartClient\n{}\nEndClient\n", &text);
let intercept_future = async move {
if let Ok(... | Rust | 0 |
uf>,
/// Print output for given component(s) to stdout/stderr
#[clap(
name = FOLLOW_LOG_OPT,
long = "follow",
multiple_occurrences = true,
)]
pub follow_components: Vec<String>,
/// Print all component output to stdout/stderr
#[clap(
long = "follow-all",
... | Rust | 0 |
import sys
from typing import Literal
from loguru import logger
def set_app_log_level(
log_level: Literal[
"TRACE", "DEBUG", "INFO", "SUCCESS", "WARNING", "ERROR", "CRITICAL"
],
) -> None:
"""Set the minimum log level for the application.
This function updates the logger to direct log output... | Python | 1 |
iewMatrix=view_mat,
projectionMatrix=env.proj_mat,
flags=p.ER_NO_SEGMENTATION_MASK,
)[2])
gifs = set_collision_marker(gifs, has_collision, se_valid)
set_collision_f... | Python | 1 |
import json
from typing import Set, Union
from datetime import datetime
from fastapi import FastAPI, HTTPException, Request, status
from pydantic import BaseModel
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse
from starle... | Python | 1 |
line.split(" -> ")
.map(|point| {
point
.split(',')
.map(|number| number.parse::<i32>().unwrap())
.collect_tuple::<Point>()
.unwrap()
})
.collect_tuple::... | Rust | 0 |
servers/http/http_services.rs
// Copyright 2021 <NAME>.
//
// 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 appli... | Rust | 0 |
l objects such as graph edges.
pub trait Reverse {
/// The type of the reversal output.
type Output;
/// Returns the result of reversal.
fn rev(self) -> Self::Output;
}
impl<A, B> Reverse for (A, B) {
type Output = (B, A);
fn rev(self) -> Self::Output {
(self.1, self.0)
}
}
/// Fo... | Rust | 0 |
Assemble for Oid<N> {
fn assemble(&self, target: &mut Fragment) {
assemble_base_7((self.0[0] * 40) + self.0[1], target);
for value in &self.0[2..] {
assemble_base_7(*value, target)
}
}
}
//------------ printable_string ----------------------------------------------
/// Re... | Rust | 0 |
result.err()
);
if result.is_ok() {
assert_eq!(
expected,
result.unwrap().to_string(),
"Original input: {} radix {}",
input,
radix
);
}
}
}
#[test]
fn it_can_calculate_signum() {
let ... | Rust | 0 |
import time
from util import *
from lxml import etree
from __init__ import *
import re
def get_home_info()->str:
driver = get_driver()
switch_to_target("https://affiliate.tiktokglobalshop.com/platform/homepage")
for _ in range(5):
try:
element = driver.find_element(by=By.XPATH,
... | Python | 1 |
.add_subplot(projection='3d')
ax.scatter(traj[:, 0], traj[:, 1], traj[:, 2], c=clrs, cmap=plt.cm.jet)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_zlim3d(min(0, traj[:, 2].min()), traj[:, 2].max())
plt.show()
input('Continue')
def main(args):
np.set_printoptions(prec... | Python | 1 |
)
gts_np = np.array(gts)[preds_np != -1]
preds_np = preds_np[preds_np != -1]
conf_m = confusion_matrix(gts_np, preds_np)
print(conf_m)
over_kill = conf_m[0, 1] / (conf_m[0, 0] + conf_m[0, 1])
miss = conf_m[1, 0] / (conf_m[1, 0] + conf_m[1, 1])
acc = accuracy_scor... | Python | 1 |
w version is actually synchronized,
// so that this function is atomic regarding version merges.
// If pushing the new version fails, the local book is still in the original state.
let b_new = b_old.merge_versions(book)?;
let data = crate::encrypt(password... | Rust | 0 |
# Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | Python | 1 |
self.r.to_iter(self.heap)
}
}
impl<'a, 'v: 'a> IntoIterator for &'a RefIterable<'v> {
type Item = Value<'v>;
type IntoIter = Box<dyn Iterator<Item = Value<'v>> + 'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
<filename>components/engine_panic/src/snapshot.rs
// Copyright 2019... | Rust | 0 |
b}', '\u{20e2}', '𐋡', 'ⷂ', 'ᆪ', 'த', '൷',
'ڬ', '◞', '㍆', '⯭', '🙖', '⒀', 'ኌ', 'ᒢ', 'ॱ', '⩺', 'ꢛ', 'ᓗ',
'𝁊', '着', '𐜫', '\u{cbc}', '㉧', '\u{2006}', '𒍻', 'ச', '𒅂', '↫', '𑗘',
'𘧓', '🔢', '⧞', '\u{488}', '\u{1e137}', '⯂', 'ꂄ', '𐨧', '🍵', 'ং', 'ᄧ',
'Ḍ', 'ꗘ', '𛉦', '㊣', 'ツ', '𝢁', '⮉', '𐀙', '𓉾', '@', ... | Rust | 0 |
;
d.insert_state_fn("SPACE", |_s : &mut State | { print!(" "); Ok(()) } );
d.insert_state_fn("SPACES", |s : &mut State | {
let n = s.stack.pop().ok_or("stack is empty for SPACES")?;
print!("{}", iter::repeat(' ').take(n.unsigned_abs() as usize).collect::<String>() );
... | Rust | 0 |
from rdkit import Chem
from rdkit import DataStructs
from rdkit.Chem.Fingerprints import FingerprintMols
import numpy as np
import argparse
parser = argparse.ArgumentParser(description="Original Vs Predicted SMILES, Tanimoto similarity check\n We are using the basic Fingerprints to calculate Tanimoto")
# Input Argumen... | Python | 1 |
_written_keys(&self) -> Vec<(Vec<u8>, u32, u32, bool)> {
panic!("get_read_and_written_keys: unsupported feature for parachain validation")
}
}
impl sp_externalities::ExtensionStore for ValidationExternalities {
fn extension_by_type_id(&mut self, type_id: TypeId) -> Option<&mut dyn Any> {
self.0.get_mut(type_id)
... | Rust | 0 |
download_all_models(ask_for_permission=True)
if isfile(resume_ckpt):
print("=> loading checkpoint '{}'".format(resume_ckpt))
checkpoint = torch.load(resume_ckpt, map_location=lambda storage, loc: storage)
assert checkpoint['state_dict']['WPCA.0.bias'].shape[0] == int(config['global_para... | Python | 1 |
s::HashSet;
use std::collections::BTreeMap;
use easy_ll;
use common::WeldRuntimeErrno;
use super::ast::*;
use super::ast::Type::*;
use super::ast::LiteralKind::*;
use super::ast::ScalarKind::*;
use super::ast::BuilderKind::*;
use super::code_builder::CodeBuilder;
use super::error::*;
use super::macro_processor;
use ... | Rust | 0 |
cmds = super::helpers::command_map(option);
let name = cmds
.get("name")
.and_then(|v| v.as_str())
.context("Unexpected missing field name")
.map_err_reply(|what| aci.create_quick_error(ctx, what, true))
.await?;
let repr = cmds
.get("repr")
.and_then(|... | Rust | 0 |
sentence] + similar_sentences)
total_perturbations += len(similar_sentences)
return PerturbedTextDataset(
data=perturbed_dataset,
metadata=None,
total_perturbations=total_perturbations,
original_dataset_size=len(self.data),
perturbations_p... | Python | 1 |
"""Minimal reproduction of the EnvironmentVariable validation bug."""
import sys
sys.path.insert(0, '/root/hypothesis-llm/envs/troposphere_env/lib/python3.13/site-packages')
from troposphere.codebuild import EnvironmentVariable
# Bug: EnvironmentVariable.validate() doesn't check for required properties
# According ... | Python | 1 |
n_size]
h, w = full_size[0:2]
if h % 8 != 0 or w % 8 != 0:
print(
"Warning: output size is not a multiple of 8. Final layer "
+ "will round size down."
)
ll_h, ll_w = train_size[0:2]
sizes = []
for i in range(num_levels):
size = (
int(rou... | Python | 1 |
)]
// Gvm { func_name: &'static str, msg_type: AppMsgType },
// #[fail(display = "AppMessageError::InvalidAppMsgType {}: Invalid message type {} from packet assembler", func_name, msg_type)]
// InvalidAppMsgType { func_name: &'static str, msg_type: AppMsgType },
// #[fail(display = "AppMessageError::Message... | Rust | 0 |
ql))
def test_grammar_from_world_can_parse_statements(self):
world = Text2SqlWorld(self.schema)
sql = [
"SELECT",
"COUNT",
"(",
"*",
")",
"FROM",
"LOCATION",
",",
"RESTAURANT",
"W... | Python | 1 |
}
}
impl MergeSorter {
fn sort<T: Ord>(l: &mut Vec<T>, start: usize, end: usize) {
if end - start <= 1 {
return;
}
let mid = (start + end) / 2;
Self::sort(l, start, mid);
Self::sort(l, mid, end);
let mut temp = Vec::<T>::new();
let (i, mut j, ... | Rust | 0 |
ize, stride, padding=(kernel_size - 1) // 2
)
else:
raise ModuleNotFoundError
self.stages.append(stage)
self._init_weight()
def forward(self, x):
output = []
for i, stage in enumerate(self.stages):
x = stage(x)
... | Python | 1 |
"|" in rest:
state_remove_value(child_dict, rest, nested)
else:
del child_dict[rest]
if len(child_dict) == 0:
del state_dict[first]
def state_get_value(state_dict, key, nested):
if "|" not in key or not nested:
return state_dict[key]
else:
... | Python | 1 |
lf::tile(texture_creator, 411, BLACK, 428, DARK_RED, &tile_set),
Self::tile(texture_creator, 412, BLACK, 428, DARK_RED, &tile_set),
Self::tile(texture_creator, 413, BLACK, 428, DARK_RED, &tile_set),
Self::tile(texture_creator, 414, BLACK, 428, DARK_RED, &tile_set),
Self::... | Rust | 0 |
cket.py" (used for auto-complete) into "test_socket.py"
filename = filename[2:]
if filename.endswith('.py'):
filename = filename[:-3]
# XXX ignoring TestCase class name (just using function name).
# Maybe we should do this with the AST, or even after the test is
# imported.
my_dis... | Python | 1 |
def get_file_url(self, path: str) -> str:
"""Get the public URL for accessing a file."""
if self.cdn_url:
# Use CDN URL if provided
encoded_path = quote(path, safe="/")
return f"{self.cdn_url.rstrip('/')}/{encoded_path}"
else:
# Use S3 endpoint ... | Python | 1 |
from rest_framework import serializers
from apps.models import Product
class ProductInlineSerializer(serializers.Serializer):
url = serializers.HyperlinkedIdentityField(view_name="apps-details", lookup_field='pk')
email = serializers.EmailField(write_only=True)
name = serializers.CharField()
clas... | Python | 1 |
UR [ 5 ( d SUR S35 e[ UR [ 5 ( d SUR S35 e[ R R
R
UR R UR ... | Python | 1 |
race_loc.loc[(trace_loc.gl == True) & (trace_loc.id == i)]
x = aux_trace.groupby('sl').x.mean()
y = aux_trace.groupby('sl').y.mean()
max_x = aux_trace.groupby('sl').x.max()
min_x = aux_trace.groupby('sl').x.min()
max_y = aux_trace.groupby('sl').y.max()
... | Python | 1 |
pub const THISTLE: Color = Color::rgb_linear(0.68668544292449951171875, 0.520995676517486572265625, 0.68668544292449951171875);
/// #FF6347 Tomato
pub const TOMATO: Color = Color::rgb_linear(1., 0.124771840870380401611328125, 0.063010029494762420654296875);
/// #40E0D0 Turquoise
pub const TURQUOISE: Color = Color::rgb... | Rust | 0 |
hods.
# Be slightly more generous with rtol than the default 1e-8
# used in z_at_value
assert allclose(z, funcs.z_at_value(func, fval, zmax=1.5),
rtol=2e-8)
# Test distance functions between two redshifts
z2 = 2.0
func_z1z2 = [lambda z1: core.Planck13._comovi... | Python | 1 |
,> {
fn set_pointer_builder<'b>(pointer: ::capnp::private::layout::PointerBuilder<'b>, value: Reader<'a,>, canonicalize: bool) -> ::capnp::Result<()> { pointer.set_struct(&value.reader, canonicalize) }
}
impl <'a,> Builder<'a,> {
pub fn into_reader(self) -> Reader<'a,> {
::capnp::traits::FromStruct... | Rust | 0 |
],
mat_arr[3][3] + mat_arr[3][0],
);
let right = Plane::new(
mat_arr[0][3] - mat_arr[0][0],
mat_arr[1][3] - mat_arr[1][0],
mat_arr[2][3] - mat_arr[2][0],
mat_arr[3][3] - mat_arr[3][0],
);
let top = Plane::new(
mat_... | Rust | 0 |
|i, handler| {
let path = temp_dir().join(format!("sallyport-test-close-{}", i));
let c_path = CString::new(path.as_os_str().to_str().unwrap()).unwrap();
// NOTE: `miri` only supports mode 0o666 at the time of writing
// https://github.com/rust-lang/miri/blob/7a2f1cadcd5120c44eda359605... | Rust | 0 |
/// public static final [TYPE_AUDIO](https://developer.android.com/reference/android/media/tv/TvTrackInfo.html#TYPE_AUDIO)
pub const TYPE_AUDIO : i32 = 0;
/// public static final [TYPE_SUBTITLE](https://developer.android.com/reference/android/media/tv/TvTrackInfo.html#TYPE_SUBTITLE)
pub ... | Rust | 0 |
});
Right(pub_fut)
}
None => Left(fready(Err(BTError::new("No central proxy created.").into()))),
}
}
}
pub use crate::io::*;
impl IO {
pub fn scan_tree(&mut self) -> (Vec<Vec<usize>>, usize) {
let n = self.scan();
let mut graph = vec![Vec::ne... | Rust | 0 |
a>>>,
pub queue_test: Arc<Mutex<VecDeque<Data>>>,
pub queue_validation: Arc<Mutex<VecDeque<Data>>>,
pub test_query_started: Arc<Mutex<bool>>,
pub validation_query_started: Arc<Mutex<bool>>,
pub is_terminated: Sender<i32>,
pub handles: Vec<Option<JoinHandle<()>>>,
}
/// Helper method to call the lambda func... | Rust | 0 |
n = self.add_occu_edit.toPlainText()
email = self.add_email_edit.toPlainText()
age = self.add_age_edit.toPlainText()
sex = self.add_sex_edit.currentText()
reference = self.add_ref_edit.toPlainText()
date_of_departure = self.add_depart_edit.toPlainText()
chief_complain = s... | Python | 1 |
"""Create sample database for fast searches and fixing broken sample paths."""
import json
import logging
import pathlib
from typing import Dict, List, Optional
import tqdm
from abletoolz.misc import DEFAULT_DB_PATH
logger = logging.getLogger(__name__)
def get_all_audio_files(path: pathlib.Path) -> List[pathlib.P... | Python | 1 |
to_string())),
),
];
let component_1 = IRComponent::new_object_from_vec(fields_1);
let fields_2 = vec![
(
"name",
Box::new(IRComponent::new_string("test".to_string())),
),
(
"name2",
... | Rust | 0 |
ply;
const PARSING_ERROR: &str = "Cannot parse the number as an unsigned 64-bit integer.";
fn main() {
// Ask the first number
print!("Enter the first number: ");
stdout().flush().unwrap();
let mut input = String::new();
stdin().read_line(&mut input).unwrap();
let x = input.trim().parse().exp... | Rust | 0 |
t blame = GitBlame::new(
&repo,
&Oid::from_str("86d242301830075e93ff039a4d1e88673a4a3020").unwrap(),
Path::new("README.md"),
14,
)
.unwrap();
assert!(
Some(Oid::from_str("86d242301830075e93ff039a4d1e88673a4a3020").unwrap())
... | Rust | 0 |
}
}
impl ::std::fmt::Debug for CPlayer_GetFriendsGameplayInfo_Response {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for CPlayer_GetFriendsGameplayInfo_Response {
fn as_ref(&self) -> ::pr... | Rust | 0 |
, // -: or +:
SensiAll, // (*)
// Parenthesis / Curly braces, Square braket
ParenLeft, ParenRight, CurlyLeft, CurlyRight, SquareLeft, SquareRight, TickCurly,
// Other Special character
Comma, Que, Colon, Scope, SemiColon,
At, At2, Hash, Hash2, Dot, DotStar,
Dollar, LineCont, EOF, Unknow... | Rust | 0 |
* `table_name` - The Table name to Create.
/// * `columns` - The column definition to create <column_name, column_type>.
fn create_table(&self, table_name: String, columns: BTreeMap<String, String>) -> Result<()>;
/// Drops a Record in the Database.
///
/// * `table_name` - The Table Name to drop from.
//... | Rust | 0 |
arry);
let parity_oveflow = self.check_flag(Flag::ParityOverflow);
let add_subtract = self.check_flag(Flag::AddSubtract);
let carry = self.check_flag(Flag::Carry);
println!(
"S = {}, Z = {}, H = {}, P/V = {}, N = {}, C = {}",
sign, zero, half_carry, parity_oveflow... | Rust | 0 |
}
#[cfg(test)]
mod tests {
use super::Hierarchy;
#[test]
fn test_hierarchy() {
let mut a = Hierarchy::new();
let root = a.add_root_node(1i32);
let sub1 = a.add_sub_node(root, 8);
let sub2 = a.add_sub_node(root, 9);
let _sub3 = a.add_sub_node(sub1, 11);
as... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.