text string | label_name string | labels int64 |
|---|---|---|
al * -BIG_EPSILON
};
point + offset
}
/// Offsets a point by an epsilon into the normal direction, depending on the angle to the given
/// direction and creates a ray from it.
///
/// If the parameter `direction` shows into the same general direction of this intersection
/// normal, the ray origin will be off... | Rust | 0 |
pub fn JS_EvalThis(ctx: *mut JSContext, this_obj: JSValue, input: *const ::std::os::raw::c_char, input_len: size_t, filename: *const ::std::os::raw::c_char, eval_flags: ::std::os::raw::c_int) -> JSValue; }
extern "C" { pub fn JS_GetGlobalObject(ctx: *mut JSContext) -> JSValue; }
extern "C" { pub fn JS_IsInstanceOf(ct... | Rust | 0 |
econstruct.
num_samples: int or None, the number of reconstructions to generate per input. If None,
only one reconstruction is generated per input.
mean: bool, if True it uses the mean of the decoder instead of sampling from it.
Returns:
A Tensor of shape [ba... | Python | 1 |
,[T->.i,)+],[T->.(E),)+],[T->.(error),)+]
// Action: (=>s5,i=>s6,error=>s7
// Goto: E=>8,T=>9
(1, vec![(TerminalSymbol::Symbol(Bracket.enum_index()), Action::Shift(5)), (TerminalSymbol::Symbol(I.enum_index()), Action::Shift(6)), (TerminalSymbol::Error(()), Act... | Rust | 0 |
ized + 'static>(&self,
mem: Self::M) -> Box<Future<Item=(Self::M, Vec<T>),Error=Self::Error>> {
Box::new(self.inner.pool.spawn_fn(move || {
let vec: Vec<T> = try!(mem.clone().into_vec());
Ok((mem, vec))
}))
}
}
impl PartialEq for Device {
fn eq... | Rust | 0 |
# Databricks notebook source
# MAGIC %md
# MAGIC ### Ingesting Pit Stops File
# COMMAND ----------
dbutils.widgets.text("p_data_source", "")
v_data_source = dbutils.widgets.get("p_data_source")
# COMMAND ----------
dbutils.widgets.text("p_file_date", "2021-03-28")
v_file_date = dbutils.widgets.get("p_file_date")
... | Python | 1 |
sh(r, ui, E, B, rqm, dt)
}
#[allow(non_snake_case)]
fn radiate<R: Rng>(&self, r: FourVector, u: FourVector, dt: f64, rng: &mut R) -> Option<(FourVector, FourVector, f64)> {
let (E, B) = self.fields(r);
let a = ELEMENTARY_CHARGE * E.norm_sqr().sqrt() / (ELECTRON_MASS * SPEED_OF_LIGHT * self.... | Rust | 0 |
::q;
#[test]
fn test_mime_precedence() {
let test = Accept(vec![]);
assert!(test.mime_precedence().is_empty());
let test = Accept(vec![qitem(mime::APPLICATION_JSON)]);
assert_eq!(test.mime_precedence(), vec!(mime::APPLICATION_JSON));
let test = Accept(vec![
... | Rust | 0 |
valid: ::std::os::raw::c_uint,
actual_type: ::std::os::raw::c_uint,
accuracy_report: ::std::os::raw::c_uint,
) -> __BindgenBitfieldUnit<[u8; 1usize], u8> {
let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize], u8> =
Default::default();
__bindgen_bit... | Rust | 0 |
vCapabilityCodeHypervisorPresent).unwrap();
if unsafe { capability.HypervisorPresent } == FALSE {
panic!("Hypervisor not present");
}
}
struct SampleCallbacks<'a> {
vp_ref_cell: &'a RefCell<VirtualProcessor>,
}
impl<'a> EmulatorCallbacks for SampleCallbacks<'a> {
fn io_port(
&mut self,... | Rust | 0 |
y local explanation
:param concept_names: list containing the names of the input concepts
:param thr: threshold to use to select important features
:return: Local Explanation
"""
# return explain_local(self, x, y, x_sample, target_class, method='weights', simplify=simplify, thr=... | Python | 1 |
import random
import math
'''
Todos os valores usados abaixo ainda
não são baseados em dados coletados de corrida,
apenas do site da Formula E.
Em versões futuras os códigos serão
melhorados e baseados em dados muito mais consistentes.
Versão 1.0.6
'''
corrida_estruturada = False
def estruturar_corrida() -> tuple:
... | Python | 1 |
pub type SHIFTCORR = crate::Reg<u8, _SHIFTCORR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SHIFTCORR;
#[doc = "`read()` method returns [shiftcorr::R](shiftcorr::R) reader structure"]
impl crate::Readable for SHIFTCORR {}
#[doc = "`write(|w| ..)` method takes [shiftcorr::W](shiftcorr::W) writer structure"]
impl ... | Rust | 0 |
#!/usr/bin/env python
from pwn import *
binary = './ropasaurusrex-85a84f36f81e11f720b1cf5ea0d1fb0d5a603c0d'
# Remote version
l = listen(0)
l.spawn_process([binary])
r = remote('localhost', l.lport)
# Uncomment for local version
# r = process(binary)
#
# If we run with a cyclic pattern, we end up with the following ... | Python | 1 |
# -*- coding: utf-8 -*-
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope th... | Python | 1 |
s()
paquetes = []
temperatura = []
presion = []
altitud = []
for linea in lineas[1:]:
valores = linea.strip().split(',')
paquetes.append(int(valores[0]))
temperatura.append(float(valores[1]))
presion.append(float(valores[2]))
altitud.append(float(va... | Python | 1 |
as well as provides
//! powerfull abstractions, allowing developers to concentrate on the more
//! relevant problems.
//!
//! _Icon families_ are represented as maps between _icons_ and _images_.The
//! type of the _icons_ of an _icon_ is what determines how it can be
//! indexed.
//!
//! ## Icons
//!
... | Rust | 0 |
];
let tree = RTree::new(
non_zero_usize!(2),
non_zero_usize!(4),
SplitStrategy::Quadratic,
)
.unwrap();
test_tree(tree, items, String::from("src/resources/2d/quadratic/"));
}
#[test]
fn rtree_3d_quadratic_test() {
let items = vec![
(
"First".to_string(... | Rust | 0 |
on',title='Regions by Ratings')
fig.update_layout(legend_title="Regions", legend_y=0.9)
fig.update_traces(textinfo='percent+label',textposition='inside')
st.plotly_chart(fig,use_container_width=True, theme=theme_plotly)
#progress bar
def ProgressBar():
st.markdown("""<style>.stprogress > di... | Python | 1 |
#!/usr/bin/env python3
# Copyright (c) 2018 Anki, Inc.
#
# 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 in the file LICENSE.txt or at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | Python | 1 |
# Generated by Django 3.2.15 on 2022-08-25 17:25
from django.db import migrations
from django.conf import settings
def delete_pending_bases(apps, schema_editor):
"""
Delete all pending bases
Note that we can't access STATUS_PENDING here because we are not using
a real model.
"""
Base = apps.... | Python | 1 |
)
logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
for removing_checkpoint in removing_checkpoints:
removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
... | Python | 1 |
tr("4th day"),\
# tr("5th day"), tr("6th day"), tr("Last day"))
# holidayWeekEnable = True
libDir = join(sourceDir, "lib")
if isdir(libDir):
sys.path.insert(0, libDir)
major, minor, patch = sys.version_info
pyVersion = f"{major}.{minor}"
pyLibDir = join(libDir, pyVersion)
if isdir(pyLibDir):
sys.path.insert(0... | Python | 1 |
# Copyright Materialize, Inc. and contributors. 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 in the LICENSE file at the
# root of this repository, or online at
#
# ht... | Python | 1 |
"""
Demo và test AI Agent
"""
import asyncio
import json
from ai_agent import AIAgent
from lstm_chatbot import LSTMChatbotUser
from sentence_transformer import QAChatbotSystem
async def demo_ai_agent():
"""
Demo chức năng AI Agent
"""
print("🚀 Bắt đầu demo AI Agent")
# Khởi tạo các model
pri... | Python | 1 |
atic is unsafe
let rb = &B; //~ ERROR use of mutable static is unsafe
let xb = XB; //~ ERROR use of mutable static is unsafe
let xrb = &XB; //~ ERROR use of mutable static is unsafe
}
use token::TokenKind;
// Each bit represents whether that bit’s TokenKind is in the set.
//
// This is a TokenSet containin... | Rust | 0 |
size: *mut size_t)
-> c_int;
}
// fs_poll.rst
handle_struct!(uv_fs_poll_t);
pub type uv_fs_poll_cb = extern "C" fn(*mut uv_fs_poll_t, c_int, *const uv_stat_t, *const uv_stat_t);
extern {
pub fn uv_fs_poll_init(loop_: *mut uv_loop_t, handle: *mut uv_fs_poll_t) -> c_int;
pub ... | Rust | 0 |
lf.filter_button.build('Current Leg', 'current-leg', active = True)
)
],
align = 'center'
)
]
),
... | Python | 1 |
'a, Statistics>,
);
fn run(&mut self, data: Self::SystemData) {
let (entities, mut game_log, names, potions, mut use_potion, mut statistics) = data;
for (entity, usage, statistic) in (&entities, &use_potion, &mut statistics).join() {
let potion_name = names.get(usage.potion);
... | Rust | 0 |
},
"risk_factors": {
"critical": critical_risks,
"high": high_risks,
"warnings": warnings
},
"next_steps": "Proceed to RAG Analysis" if verdict == "PASS" else "Review social risks"
}
... | Python | 1 |
== Some(rollup_type_hash))
}
pub fn search_rollup_state(
rollup_type_hash: &[u8; 32],
source: Source,
) -> Result<Option<GlobalState>, SysError> {
let index = match QueryIter::new(load_cell_type_hash, source)
.position(|type_hash| type_hash.as_ref() == Some(rollup_type_hash))
{
Some(i)... | Rust | 0 |
# Copyright 2017 The TensorFlow 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 applica... | Python | 1 |
machine.handle_warp_message(&mut state, Message::Action(Value::from(2)));
assert!(!terminate);
assert!(matches!(result, Ok(Some(v)) if v == Value::from(2)));
}
#[test]
fn event_dl_ignore_invalid_message() {
let machine = EventStateMachine::new(
StandardSchema::OfKind(ValueKind::Int32),
Sc... | Rust | 0 |
nt) = msg.governance_percent {
if governance_percent > Uint64::new(100) {
return Err(ContractError::IncorrectGovernancePercent {});
};
governance_percent
} else {
Uint64::zero()
};
let max_spread = if let Some(max_spread) = msg.max_spread {
if max_spread.... | Rust | 0 |
pro':
st.subheader("📝 Trade History")
st.dataframe(pf.trade_history)
# Trade Signals (Records in a human-readable format)
st.subheader("📌 Trade Signals")
st.dataframe(pf.trades.records_read... | Python | 1 |
ate, 0x80, data.as_mut_ptr(), &mut cb_data);
if ykrc != ErrorKind::Ok {
cb_data = 0;
}
let mut tnow = time(ptr::null_mut());
res = {
// TODO(tarcieri): get rid of memcpy and pointers, replace with slices!
#[allow(trivial_casts)]
_set_met... | Rust | 0 |
::Other,
"unknown error",
))),
}
}
}
<filename>src/lib.rs<gh_stars>0
//! MC Named Binary Tag type.
extern crate byteorder;
extern crate flate2;
extern crate linked_hash_map;
/* Re-export the core API from submodules. */
pub use blob::Blob;
pub use error::{Error, Result};... | Rust | 0 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBnReLU(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, pad=1, dilation=1):
super(ConvBnReLU, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, ... | Python | 1 |
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Stream(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, nullable=False)
song_id = db.Column(db.Integer, nullable=False)
timestamp = db.Column(db.DateTime, default=db.func.current_timestamp())
dur... | Python | 1 |
std::test]
async fn terminates() {
future::poll_fn(super::terminates).await;
}
#[async_std::test]
async fn waits_for_other() {
future::poll_fn(super::waits_for_other).await;
}
#[async_std::test]
async fn wakeup() {
let (a, b) ... | Rust | 0 |
tle, EOF);
let mut body = String::new();
stdin().read_to_string(&mut body).unwrap();
let _ = create_post(&connection, title, &body, user_id);
println!("\nSaved draft {}", title)
}
#[cfg(not(windows))]
const EOF: &'static str = "CTRL+D";
#[cfg(windows)]
const EOF: &'static str = "CTRL+Z"... | Rust | 0 |
t = int(input())
for _ in range(t):
n, k = map(int, input().split())
st = list(map(int, input().split()))
count = 0
for j in st:
if j <= 0:
count += 1
if count >= k:
print("NO")
else:
print("YES")
| Python | 1 |
# Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
# An input string is valid if:
# Open brackets must be closed by the same type of brackets.
# Open brackets must be closed in the correct order.
# Every close bracket has a corresponding open brack... | Python | 1 |
env.limit - v_5;
env.cursor = env.limit_backward;
if !(context.i_measure > 2){
return false;
}
'lab5: loop {
let v_6 = env.cursor;
'lab6: loop {
let v_7 = env.cursor;
if !r_remove_first_order_prefix(env, context) {
break 'lab6;
... | Rust | 0 |
import turtle as tl
import time
def drawGap(): #绘制数码管间隔
#提起画笔
tl.pu()
# 数码管间隔
tl.fd(9)
def drawLine(draw): #绘制单段数码管
drawGap()
tl.pendown() \
if draw else tl.penup()
tl.fd(40)
drawGap()
tl.right(90)
def drawDigit(d): #根据数字绘制七段数码管
# 每个数字由7段数码管组成
drawLine(True) if ... | Python | 1 |
import cv2
from handtracker import HandTracker
from utils import get_current_track
def main():
_ = get_current_track()
cap = cv2.VideoCapture(0)
tracker = HandTracker()
while cap.isOpened():
success, frame = cap.read()
if not success:
break
frame = cv2.flip(frame... | Python | 1 |
elf) -> VpnServiceState;
/// The state of the plugin.
#[cfg(any(feature = "v1_2", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_2")))]
fn set_state(&self, state: VpnServiceState);
/// Whether to watch for D-Bus peer's changes.
#[cfg(any(feature = "v1_2", feature = "dox")... | Rust | 0 |
types::DisplayName,
}
impl_de_ser!(VideoPlayback, "video-playback", channel_login);
impl pubsub::Topic for VideoPlayback {
#[cfg(feature = "twitch_oauth2")]
const SCOPE: &'static [twitch_oauth2::Scope] = &[];
fn into_topic(self) -> pubsub::Topics { super::Topics::VideoPlayback(self) }
}
/// Statistics a... | Rust | 0 |
from flask import Flask, request, jsonify
from model import compare_images # Import the function from model.py
app = Flask(__name__)
# Route to return the list of members
@app.route('/members', methods=['GET'])
def get_members():
return jsonify({"members": ["shreyansh", "suresh", "shreya"]})
# Route to compare ... | Python | 1 |
ust Cook Book"), 1);
book_prices_map.insert(String::from("Go Cook Book"), 2);
// book_prices_map: {"Go Cook Book": 2, "Rust Cook Book": 1}
let book_name_key: &str = "Rust Cook Book";
let res = book_prices_map.get(book_name_key);
println!("《{book_name_key}》 book's price is {:?}", res)
// 《Rus... | Rust | 0 |
import heapq
import math
def a_star():
# Define the initial state of the city map as a 2d tuple
initial_state = ((19, 'x', 3, 'x', 'x', 'x', 13, 'x', 12, 'x'),
('x', 'x', 8, 'x', 15, 18, 11, 12, 'x', 7),
('x', 8, 'x', 'x', 15, 20, 17, 12, 2, 8),
... | Python | 1 |
_lch = Color::new_lcha(32.3, 133.81, 306.28, 1.0);
assert_eq!(blue_lch.to_rgb_string(), "rgb(0, 0, 255)");
let magenta_lch = Color::new_lcha(60.32, 115.54, 328.23, 1.0);
assert_eq!(magenta_lch.to_rgb_string(), "rgb(255, 0, 255)");
}
#[test]
fn color_interpolate_lch() {
let red = Color::new_string("rgb... | Rust | 0 |
rt(
ctx: &Context,
guild_id: Option<GuildId>,
_channel_id: Option<ChannelId>,
s: &str,
) -> Result<Self, Self::Err> {
let roles = ctx
.cache
.guild_roles(guild_id.ok_or(RoleParseError::NotInGuild)?)
.await
.ok_or(RoleParseError:... | Rust | 0 |
= attr.ib(type=str)
path_to_codebase = attr.ib(type=str)
rules = attr.ib(type=str)
include_paths = attr.ib(type=List[str], default=None)
exclude_paths = attr.ib(type=List[str], default=None)
def refactor_codebase(self, dry_run: bool = True) -> List[PiranhaOutputSummary]:
"""
Applie... | Python | 1 |
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
from typing import List, Optional, Union
from airbyte_cdk.sources.streams import Stream
def get_primary_key_from_stream(stream_primary_key: Optional[Union[str, List[str], List[List[str]]]]) -> List[str]:
if stream_primary_key is None:
return []
... | Python | 1 |
rd(&mut self, register: &Register16, value: u16) {
match register {
Register16::AF => {
self.data[0] = value;
}
Register16::BC => {
self.data[1] = value;
}
Register16::DE => {
self.data[2] = value;
... | Rust | 0 |
let mut rng = rand::weak_rng();
let region = [
rng.gen_range(1, dims[0] + 1),
rng.gen_range(1, dims[1] + 1),
rng.gen_range(1, dims[2] + 1),
];
let origin = [
rng.gen_range(0, (dims[0] - region[0]) + 1),
rng.gen_range(0, (dims[1] - region[1]) + 1),
rng.g... | Rust | 0 |
indices, num_batch, batch_dim)
shard_arg_handlers = {} # Shard an argument to a distributed array
for a in array_types:
shard_arg_handlers[a] = _shard_array
shard_arg_handlers[ShapedArray] = _shard_abstract_array
shard_arg_handlers[ShapeDtypeStruct] = _shard_abstract_array
shard_arg_handl... | Python | 1 |
/// allowed).
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
let _version = value.get(0).ok_or(CryptoError::BadLength {
step: "get stream version",
actual: 0,
expected: 1,
})?;
let expected_len = 33;
if value.len() != expected_len {
... | Rust | 0 |
),
HASH_SIZE * 8
);
}
#[test]
fn test_pors() {
assert!(PORS_K > 0);
assert!(PORS_K <= PORS_T);
}
#[test]
fn test_gravity() {
assert!(GRAVITY_C + MERKLE_H * GRAVITY_D <= 64);
}
}
<reponame>benkelaar/libunftp
//! The RFC 959 No Operation (`NOOP`) c... | Rust | 0 |
b283c, 0x9541ff0d,
0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8,
];
pub const TABLE_DEC3: [u32; 256] = [
0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b,
0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4... | Rust | 0 |
import base64
import binascii
from Crypto.Util.Padding import pad
from src.decryption import get_cipher
def encrypt_private_key(private_key: str, password: str) -> str:
private_key = private_key.strip()
if private_key.startswith("0x"):
private_key = private_key[2:]
if len(private_key) % 2 != 0:
... | Python | 1 |
"""process rgb, scan and cad depth, all same with Stage I:"""
item = self.data[idx]
scene_id = item['scene_id']
frame_id = item['frame_id']
rgb_image = self.load_image(item['conditioning_image'], "RGB")
scan_depth = self.load_depth_image(item['scan_depth'])
cad_depth =... | Python | 1 |
the problem
raise error
return tuple(guides[name] for name in layers)
def trim(self, layers: Optional[Iterable[str]] = None) -> None:
if layers is None:
layers = self.registered_layers
else:
for name in layers:
self.verify(name)
... | Python | 1 |
);
attr
}),
Entry::Chapter(chapter_ref, _) => chapter_ref.upgrade().map(|chapter| {
let mut attr = attributes.file_attr();
attr.set_size(4096u64);
attr.set_blocks(8u64);
attr.set_mode(libc::S_IFDIR as u32 | 0o555);... | Rust | 0 |
# Welcome message. informing the user of the parameters.
print ("Lets play a little game and see if you can guess my number.")
print ('The number will be between 1 & 100. ')
print ("Your guidance system will be the classic too big & too small")
#Defines the random module for this speciifc code so we can generate a ra... | Python | 1 |
BinOp::LtInt | BinOp::LtFloat => self.print_bin_op(left, right, "<"),
BinOp::LtEqInt | BinOp::LtEqFloat => self.print_bin_op(left, right, "<="),
// TODO: https://dmitripavlutin.com/how-to-compare-objects-in-javascript/
BinOp::Eq => unsupported("Equality operator"),
BinOp:... | Rust | 0 |
jni_method) = __jni_env.require_class_method("java/security/cert/CertificateRevokedException\0", "getInvalidityDate\0", "()Ljava/util/Date;\0");
__jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [getExtensions](https://developer.android... | Rust | 0 |
first line
/// (with nothing else). Notice that you must not import the attribute but
/// use its full path.
/// - Then the body of the invocation. Both syntaxes are allowed.
/// - Then the `)]` on its own line, followed immediately by
/// `//duplicate_end`.
/// I.e. `)]//duplicate_end`
/// - Then the item to... | Rust | 0 |
from django.views import View
from comment.models import BlockedUser, BlockedUserHistory, Comment
from comment.mixins import CanBlockUsersMixin
from comment.responses import UTF8JsonResponse, DABResponseData
from comment.messages import BlockUserError
class BaseToggleBlockingView(DABResponseData):
response_class... | Python | 1 |
}
#[doc(hidden)]
pub static LATEST_BLOCK_KEY: LATEST_BLOCK_KEY = LATEST_BLOCK_KEY {
__private_field: (),
};
impl ::lazy_static::__Deref for LATEST_BLOCK_KEY {
type Target = Hash;
fn deref(&self) -> &Hash {
#[inline(always)]
fn __static_ref_initialize() -> Hash {
Hash::digest(Byte... | Rust | 0 |
_sourced.rs
#![allow(dead_code)]
use std::marker::PhantomData;
use cqrs::EventSourced as _;
use cqrs_codegen::{Aggregate, Event, EventSourced};
#[derive(Aggregate, Default)]
#[aggregate(type = "aggregate")]
struct Aggregate {
id: i32,
event1_applied: bool,
event2_applied: bool,
event3_applied: bool,
... | Rust | 0 |
me : AppName
The name of the game
Returns
-------
Dict
Cascaded result dictionary, format:
{model_name:{difficulty:{metric_name:value}}}
"""
# Pytorch multiprocess settings
mp.set_start_method("spawn")
manager = mp.Manager()
... | Python | 1 |
nable to read config file: {filepath}: {e}'
logging.error(msg)
return { 'config_error': msg }, None
return {}, content
else:
if ext not in [ '.json', '.yaml' ]:
return { 'config_error': 'bad file type' }, None
try:
... | Python | 1 |
import pytest
from mergekit.common import ModelPath, ModelReference
class TestModelReference:
def test_parse_simple(self):
text = "hf_user/model"
mr = ModelReference.parse(text)
assert mr.model == ModelPath(path="hf_user/model", revision=None)
assert mr.lora is None
assert... | Python | 1 |
# Follow the obstacle contour until a clear path to the goal is found
dx_goal = self.goal[0] - current_pos[0]
dy_goal = self.goal[1] - current_pos[1]
dist_to_goal = (dx_goal ** 2 + dy_goal ** 2) ** 0.5
# Check if there is a clear path to the goal
if self.costmap[self.hi... | Python | 1 |
or the Known
/// Pinned Host.
pub include_subdomains: Annotated<bool>,
/// Indicates the hostname that the UA noted when it noted the Known Pinned Host. This field
/// allows operators to understand why Pin Validation was performed for, e.g., foo.example.com
/// when the noted Known Pinned Host wa... | Rust | 0 |
from typing import Dict
from soda.execution.check.check import Check
from soda.execution.check_outcome import CheckOutcome
from soda.execution.metric.metric import Metric
from soda.execution.metric.reference_metric import ReferenceMetric
KEY_INVALID_REFERENCE_COUNT = "invalid_reference_count"
class ReferenceCheck(C... | Python | 1 |
<protobuf::FileScanExecConf, Self::Error> {
let file_groups = conf
.file_groups
.iter()
.map(|p| p.as_slice().try_into())
.collect::<Result<Vec<_>, _>>()?;
Ok(protobuf::FileScanExecConf {
file_groups,
statistics: Some((&conf.statis... | Rust | 0 |
[doc = " @event{This function is used during authentication procedures\\, see the list of events in the documentation of @ref sd_ble_gap_authenticate.}"]
#[doc = " @endevents"]
#[doc = ""]
#[doc = " @mscs"]
#[doc = " @mmsc{@ref BLE_GAP_PERIPH_BONDING_PK_CENTRAL_OOB_MSC}"]
#[doc = " @mmsc{@ref BLE_GAP_PERIPH_LESC_BONDIN... | Rust | 0 |
arg_tys;
let mut attrs = x86_64.attrs;
if x86_64.sret {
let llretptr = GEPi(bcx, llargbundle, [0u, n]);
let llretloc = Load(bcx, llretptr);
llargvals = ~[llretloc];
atys = vec::tail(at... | Rust | 0 |
79, 8.91),
(2009.0, 1.0, 12925.41, 9209.2, 1558.494, 996.287, 9926.4, 212.671, 1592.8, 0.22, 8.1, 306.547, 0.94, -0.71),
(2009.0, 2.0, 12901.504, 9189.0, 1456.678, 1023.528, 10077.5, 214.469, 1653.6, 0.18, 9.2, 307.226, 3.37, -3.19),
(2009.0, 3.0, 12990.341, 9256.0, 1486.398, 1044.088, 10040.6, 216... | Python | 1 |
OperandSize::Dword,
)
}
#[test]
fn ltr_4() {
run_test(
&Instruction {
mnemonic: Mnemonic::LTR,
operand1: Some(IndirectScaledIndexed(
EDI,
ECX,
Four,
Some(OperandSize::Word),
None,
... | Rust | 0 |
n = int(input())
for i in range(n-1,-1,-1):
print(" "*i, end="")
opp = n-i
print("*"*(opp+opp-1))
for i in range(n):
print(" "*i, end="")
opp = n-i
print("*"*(opp+opp-1))
| Python | 1 |
onse.status_code == 404:
raise NotFoundError(
typing.cast(
typing.Optional[typing.Any],
parse_obj_as(
type_=typing.Optional[typing.Any], # type: ignore
object_=_response.json(),
... | Python | 1 |
import sys
import time
import socket
import datetime
myAddress = '' #means 'all'
myPort = 21568
hisPort = 5
hisAddress = ''
numPkts = 0
delay = 0
if len(sys.argv) == 6:
hisAddress = (sys.argv[1])
pktInterval = (sys.argv[2])
numPkts = int(sys.argv[3])
delay = int(sys.argv[4])
d_flag = i... | Python | 1 |
from fastapi import FastAPI, Path
from typing import Annotated
app = FastAPI()
# python -m uvicorn module_16_3:app
users = {'1': 'Имя: Example, возраст: 18'}
@app.get('/users')
async def get_all_users() -> dict:
return users
@app.post('/users/{username}/{age}')
async def new_user(username, age: str) -> str:
... | Python | 1 |
.map_err(DeviceRegistrationError::MmioInsert)?;
}
None => {
mmio_bus
.insert(
Arc::new(Mutex::new(goldfish_bat)),
mmio_base,
devices::bat::GOLDFISHBAT_MMIO_LEN,
)
.map_err(DeviceRegist... | Rust | 0 |
,
NodeId,
hello::{
HelloMetadata,
},
key_exchange,
};
#[cfg(feature = "enable_server")]
use crate::comms::{
hello::{
mesh_hello_exchange_receiver
},
};
use crate::spec::SerializationFormat;
use crate::crypto::{
KeySize,
PrivateEncryptKey,
EncryptKey,
};
use crate::err... | Rust | 0 |
+LVD", "+ISO", "", "-CLVD", "-LVD", "DC"]
alignments = ["TC", "TC", "RM", "RM", "BC", "BC", "LM", "LM", "TC"]
gmt.psxy(in_columns=(lons, lats), N=True, S="p6p", W="1p,0", R=R, J=J)
rows = []
if labels:
farg = ["-F+f+j"]
for lon, lat, text, align in zip(lons, lat... | Python | 1 |
m("EXAMPLE RETURN"))
}<filename>src/configs/memory_usage.rs
use crate::config::ModuleConfig;
use serde::Serialize;
use starship_module_config_derive::ModuleConfig;
#[derive(Clone, ModuleConfig, Serialize)]
pub struct MemoryConfig<'a> {
pub threshold: i64,
pub format: &'a str,
pub style: &'a str,
pub s... | Rust | 0 |
/bin/clickhouse", "local", "--stacktrace", "-q", query]
)
assert out == "1\ta\n2\tbb\n3\tccc\n"
node.query("drop table test.distr_3")
def test_remove_replica(started_cluster):
node.query("drop table if exists test.local_4 sync")
node.query("drop table if exists test.distr_4 sync")
node.query... | Python | 1 |
t accept a 0 bid
if amount == Uint128(perfect_proposal) {
return Err(StdError::generic_err(
"You can't expect getting lesser or equal to what you propose",
));
}
// if bid is greater than client estimation, send the tokens back
if amount.u128() > state.average_bid {
... | Rust | 0 |
/// An Item for `MtcList`. A struct implementing `MtcItem` is usually defined for a specific time and it has a `ItemState`.
pub trait MtcItem {
/// Returns true if the item is for a given date.
///
/// # Example
/// ```
/// use chrono::prelude::*;
/// use mtc::{MtcItem,ItemState};
///
... | Rust | 0 |
_to_queue(
&input_queue,
&vec![input_buffer.deref()].as_slice(),
&vec![].as_slice(),
)
.unwrap();
input_server.notify_queue(&input_queue, input_head).unwrap();
let output_queue = device.virtio_device.get_queue(1);
let mut o... | Rust | 0 |
try:
from userbot.modules.sql_helper import SESSION, BASE
except ImportError:
raise AttributeError
from sqlalchemy import Column, UnicodeText, Numeric, String
class Notes(BASE):
__tablename__ = "notes"
chat_id = Column(String(14), primary_key=True)
keyword = Column(UnicodeText, primary_key=True, n... | Python | 1 |
e about MEX, I suggest you watch this
/// [video](https://www.youtube.com/watch?v=JDuVLyKn7Yw).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MexSet<T: Ord + Hash + Copy + Unsigned + Num> {
set: FxHashSet<T>,
complement: BTreeSet<T>,
mex_upper_bound: T,
}
impl<T: Ord + Hash + Copy + Unsigned + Num> M... | Rust | 0 |
aft<D, R, E, S> as Actor>::Context: actix::dev::ToEnvelope<Raft<D, R, E, S>, C>
{
let local_id = self.id;
let proximity = self.clone();
debug!(?proximity, raft_rpc = ?rpc, "Submitting Raft RPC to local Raft.");
Box::new(
self.raft.send(rpc)
.map_err(move ... | Rust | 0 |
src/io/write_and_flush.rs
use std::io::{BufRead, Cursor, Read, Write};
use crate::error::Error;
use mco::net::TcpStream;
/// Atomic operation that writes the full buffer to the stream, flushes the stream, and then
/// clears the buffer (even if either of the two previous operations failed).
pub struct WriteAndFlush<'a... | Rust | 0 |
import streamlit as st
@st.cache_data(show_spinner=False)
def add_rows_stores(df):
import pandas as pd
# List of unique stores required for each combination
required_stores = df['Υποκατάστημα'].dropna().unique()
required_stores_df = pd.DataFrame(required_stores, columns=['Υποκατάστημα'])
# Identi... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.