text string | label_name string | labels int64 |
|---|---|---|
from pydantic import BaseModel, ValidationError
from epog.utils.gpt_helper import ChatGPT
class Step(BaseModel):
explanation: str
output: str
def tojson():
return {
"type": "object",
"properties": {
"explanation": {
"type": "string"
... | Python | 1 |
client = match spawn.spawn().await{
Ok(p) => p,
Err(e) => {
println_err!("connect error : {}", e);
continue;
},
};
let result = match client.ls(&cwd).await{
Ok(p) => p,
Err(_) => {
println_err!("command execute faild");
continue;
},
};
let mut files : Vec<FileIn... | Rust | 0 |
import pyrebase
import paho.mqtt.client as mqtt
import requests
import shodan
import time
import os
def get_lat_lon(ip):
r = requests.get("https://freegeoip.net/json/" + ip)
json_response = r.json()
if json_response['latitude'] and json_response['longitude']:
lat = json_response['latitude... | Python | 1 |
t, s_prefix = self._get_bucket_key(source)
d_bucket, d_prefix = self._get_bucket_key(dest)
# copy source to destination and then delete source
copy_source = {"Bucket": s_bucket, "Key": s_prefix}
retries = 0
for n in range(self.retries):
try:
res = self... | Python | 1 |
<f32>,
/// LegPaymentStreamFinalRateRoundingDirection
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "40346")]
pub leg_payment_stream_final_rate_rounding_direction: Option<LegPaymentStreamFinalRateRoundingDirection>,
/// LegPaymentStreamFinalRatePrecision
#[serde(skip_serializing_if = "Option:... | Rust | 0 |
]
pub fn make_rx(args: TokenStream, input: TokenStream) -> TokenStream {
let parsed = syn::parse_macro_input!(input as ItemStruct);
let name = syn::parse_macro_input!(args as syn::Ident);
rx_state::make_rx_impl(parsed, name).into()
}
<filename>crates/mun_syntax/src/syntax_kind/generated.rs
//! Generated fi... | Rust | 0 |
from rest_framework.serializers import (
ModelSerializer,
SerializerMethodField,
StringRelatedField,
)
from ..models import Superinvestor, SuperinvestorActivity, SuperinvestorHistory
class SuperinvestorSerializer(ModelSerializer):
class Meta:
model = Superinvestor
exclude = [
... | Python | 1 |
phase in match.kill_chain_phases:
if phase.kill_chain_name == "mitre-attack":
xphase = phase.phase_name
shortlist.append((xid, xphase, match.description))
full_matrix_listing = copy.deepcopy(self.full_matrix)
construct = list()
for tactic in full_... | Python | 1 |
);
std::fs::create_dir_all(config.ledger_db.clone()).expect("Could not create ledger dir");
LedgerDB::create(config.ledger_db.clone()).expect("Could not create ledger_db");
let (block, transactions) = transactions_fetcher
.get_origin_block_and_transactions()
... | Rust | 0 |
osition)
.with(Size::xy(0.2, 0.2))
.with(ShapeColor(color))
}
fn build_circle(position: Position, color: Color) -> impl Built<Self> {
EntityBuilder::new(Self)
.with(position)
.with(Size::xy(0.2, 0.2))
.with(Shape::Circle2D)
.with(S... | Rust | 0 |
from fastapi import FastAPI, Depends
from library_mgt.controllers import admin, management
from configuration.config import LibrarySettings
library_app = FastAPI()
library_app.include_router(admin.router)
library_app.include_router(management.router)
def build_config():
return LibrarySettings()
@library_app.ge... | Python | 1 |
import os,sys,time,os,json,requests,json
from colorama import Fore,Back,init
from requests import get,post
from urllib import request
def autoketik(s):
for c in s + "\n":
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.008)
B = Fore.BLUE
W = Fore.WHITE
R = Fore.RED
G = Fore.GREEN
BL = ... | Python | 1 |
stp(PreIndexed, X14, X15, SP, -16)
.stp(PreIndexed, X16, X17, SP, -16)
.stp(PreIndexed, X18, X19, SP, -16)
.stp(PreIndexed, X20, X21, SP, -16)
.stp(PreIndexed, X22, X23, SP, -16)
.stp(PreIndexed, X24, X25, SP, -16)
.stp(PreIndexed, X26, X27, SP, -16)
.stp(PreIndex... | Rust | 0 |
::from_timestamp(since_the_epoch().as_secs() as i64, 0);
let then = NaiveDateTime::from_timestamp(s as i64, 0);
let diff = then - now;
let ht = chrono_humanize::HumanTime::from(diff);
format!("{}", ht)
})
}
fn since_the_epoch() -> Duration {
let start = SystemTime::now();
... | Rust | 0 |
, e, p.1, p.2), wght)));
let dK5dI = dK5dI2.extend(vec![&forward.extend_using(|&(a1,a2,a3,a5)| a1 as u64, |t1, t2| t1.le(t2)),
&forward.extend_using(|&(a1,a2,a3,a5)| a2 as u64, |t1, t2| t1.le(t2)),
&forward.extend_using(|&... | Rust | 0 |
("P2", c_float),
("P3", c_float),
("IGP", c_float)]
class FCAMVALUESTYPE(Structure):
_fields_ = [("exposure_nr", c_char*4), # char array;
("stock", c_int), # integer; { exposure stock }
("seriessize", c... | Python | 1 |
import numpy as np
import os
import imageio
from PIL import Image
blender2opencv = np.array(
[[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
def get_instrinsic(filepath):
try:
intrinsic = np.loadtxt(filepath).astype(np.float32)[:3, :3]
return intrinsic
except ValueError:
... | Python | 1 |
(short = "z", long, default_value = "Lanczos3", parse(try_from_str = parse_similar_image_filter), help = "Hash algorithm (allowed: Lanczos3, Nearest, Triangle, Faussian, Catmullrom)")]
image_filter: FilterType,
#[structopt(short = "c", long, default_value = "8", parse(try_from_str = parse_image_hash_siz... | Rust | 0 |
any.
var1: SourceSpan,
#[highlight(snip)]
// Anything that's Clone + Into<SourceSpan> can be used here.
var2: (String, usize, usize),
// Now with member source names
filename: String,
second_message: String,
#[snippet(src, filename, second_message)]
... | Rust | 0 |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.WGL import _types as _cs
# End users want this...
from OpenGL.raw.WGL._types import *
from OpenGL.raw.WGL import _errors
from OpenGL.constant import Constant as _C
import ctype... | Python | 1 |
s` : spectral flatness.
- :code:`spectral_rolloff` : spectral rolloff.
- :code:`spectral_flux` : spectral flux.
- :code:`spectral_mean` : spectral mean.
- :code:`spectral_rms` : spectral root mean square.
- :code:`spectral_std` : spect... | Python | 1 |
d_log(log_view)
gui.mainloop()
def load_log(widget):
try:
with open("activity_log.txt", "r") as f:
widget.delete(1.0, tk.END)
widget.insert(tk.END, f.read())
except FileNotFoundError:
widget.delete(1.0, tk.END)
widget.insert(tk.END, "No log found. \n")
def c... | Python | 1 |
org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// li... | Rust | 0 |
rgs: Any
) -> Metric:
"""Compute fluency score.
Args:
generations: Any number of generated strings from the model.
Returns:
Average n-gram entropy across generations. Can specify multiple ns by
setting the ns= kwarg. By default, uses 2-grams and 3-grams.
"""
if desc is Non... | Python | 1 |
= np.asarray(coords).astype(np.float64)
assert coords_array.shape[1] == 3
ats = [x[0] for x in cleans]
m = Chem.MolFromSmiles(smi)
m1 = Chem.AddHs(m)
AllChem.EmbedMolecule(m1)
c1 = m1.GetConformer()
for k in range(m1.GetNumAtoms()):
... | Python | 1 |
/// Integer representing failure in gdscript
const GODOT_ERROR: i64 = 1;
/// Interface exported to Godot
///
/// The map must first be filled by using e.g. `add_point`, `connect_points`,
/// `add_square_grid`...
///
/// And then you must call `recalculate` on it.
#[derive(NativeClass)]
#[inherit(Reference)]
pub struct... | Rust | 0 |
TestActivityCtx.read_progress_bar(domain, group_by=groupby, progress_bar=progress_bar)
self.assertEqual(len(groups), 3)
self.assertEqual(len(progressbars), 3)
# format the read_progress_bar result to get a dictionary under this
# format: {activity_state: group_name}; the original format... | Python | 1 |
_with_self_act%d.png' % idx))
shutil.copyfile(src=os.path.join(original_img_dir, 'prototype-self-act%d.npy' % prototypes_to_keep[idx]),
dst=os.path.join(dst_img_dir, 'prototype-self-act%d.npy' % idx))
bb = np.load(os.path.join(original_img_dir, 'bb%d.np... | Python | 1 |
/ }
// }
// pub fn maybe_contains_value(&self, v: i64) -> bool {
// self.range.0 <= v && v <= self.range.1
// }
// pub fn max(&self) -> i64 {
// self.range.1
// }
// pub fn num_rows(&self) -> usize {
// self.num_rows
// ... | Rust | 0 |
from odoo import fields, models, api, tools
class SaleProduct(models.Model):
_inherit = 'product.template'
url_links = fields.Text(string='Paste URL Links')
def get_extra_images(self):
pass
| Python | 1 |
YPE_A::PRBSTYPE_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the f... | Rust | 0 |
#!/usr/bin/env python3
# Copyright 2018 Mitsubishi Electric Research Laboratories (Takaaki Hori)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import codecs
import logging
import sys
import six
is_python2 = sys.version_info[0] == 2
def get_parser():
parser = argparse.ArgumentPars... | Python | 1 |
let cpu_control_params = Self::get_cpu_params(
&self.cpu_driver_path,
&proxy,
self.capacitance,
self.min_cpu_clock_speed,
)
.await
.context("Failed getting CPU params")?;
inspect_data.set_cpu_control_params(&cpu_control_params);
... | Rust | 0 |
// cursor.seek(SeekFrom::Start(pos + offset))?;
// Ok((hash, read_param(cursor, fd)?))
// })
// .collect::<Result<Vec<_>, Error>>()?;
Ok(ParamKind::Struct(ParamStruct(params)))
}
_ => Err(Error::new(
ErrorKi... | Rust | 0 |
t;
width: 20px;
border-left: none;
}
QComboBox QAbstractItemView {
border: 1px solid #dcdfe6;
border-radius: 4px;
background-color: white;
selection-background-color: #e6f2ff;
selectio... | Python | 1 |
#
# Copyright (C) 2024-present by TeamYukki@Github, < https://github.com/TeamYukki >.
#
# This file is part of < https://github.com/TeamYukki/YukkiMusicBot > project,
# and is released under the "GNU v3.0 License Agreement".
# Please see < https://github.com/TeamYukki/YukkiMusicBot/blob/master/LICENSE >
#
# All rights ... | Python | 1 |
_hex: array).unwrap(),
*format!("{:#X?}", array),
);
})
}
test_case!([0u16, 1, 2, u16::MAX / 2, u16::MAX]);
test_case!([0u32, 1, 2, u32::MAX / 2, u32::MAX]);
test_case!([0u64, 1, 2, u64::MAX / 2, u64::MAX]);
test_case!([0u128, 1, 2, u128::MAX / 2, u128::MAX]);
... | Rust | 0 |
#MODUULI 1 TEHTÄVÄ 1
print("Hei, Leevi Tiihonen!")
| Python | 1 |
[(device_name, diff)
for device_name, diff in all_diffs.iteritems()]
diff_list = sorted(diff_list, key=lambda x: len(x[1]))
# print diff with max no. of lines
device_name, diff = diff_list[-1]
PrintReminder.purple('Showing one of the biggest diff at %s' % device_name)
print(diff)
... | Python | 1 |
EmptySlots: ptr::null_mut(),
PrimarySpace: ptr::null_mut(),
SecondarySpace: ptr::null_mut(),
EmptySlotsFile: 0,
AllocatedSlots: 0,
QuitChecks: false,
DeformattedRTFs: 0,
DeformattedHTMs: 0,
}
}
}
#[derive(Default, Debug, Co... | Rust | 0 |
serde(skip_serializing_if = "Vec::is_empty")]
joints: Vec<Joint>,
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
proofchain_balls: Vec<ProofBalls>,
}
#[derive(Serialize, Deserialize)]
struct ProofBalls {
ball: String,
unit: String,
parent_balls: Vec<String>,
#[serde(s... | Rust | 0 |
, true => 0b00000010
0xDE, 0xAD, 0xBE, 0xEF, // 0xDEADBEEF
]),
};
assert_eq!(Foo::decode(frame).is_err(), true);
}
}
<filename>grpc/hello-grpc-rust/src/landing/server.rs
#![allow(dead_code)]
#![allow(unused_variables)]
use std::collections::HashMap;
use std::env;
use std::error:... | Rust | 0 |
alloc(cs.namespace(|| "num"), || fr)
}
#[cfg(test)]
mod tests {
use super::kdf;
use crate::circuit::test::TestConstraintSystem;
use crate::crypto;
use crate::fr32::fr_into_bytes;
use crate::util::bytes_into_boolean_vec;
use bellperson::ConstraintSystem;
use fil_sapling_crypto::circuit::bool... | Rust | 0 |
ocumentation": "⌥⌘?",
"Run": "⌘R",
"Run…": "⌥⌘R",
"Test": "⌘T",
"Test…": "⌥⌘T",
"Profile": "⌘I",
"Profile…": "⌥⌘I",
"Analyze": "⌃⌘B",
"Analyze…": "⌃⌥⌘B",
"Archive": "not set",
"Build For Running": "⇧⌘R",
"Build For Testing": "⇧⌘U",
... | Python | 1 |
.push(post);
}
Ok(posts)
}
}
impl std::panic::UnwindSafe for DBClient {}
impl std::panic::RefUnwindSafe for DBClient {}
#[cfg(test)]
#[allow(non_snake_case)]
mod tests {
use super::*;
fn run_async<F: std::future::Future>(f: F) {
let rt = tokio::runtime::Runtime::new().un... | Rust | 0 |
{
let mut build = Response::build();
if let Some(responder) = self.0 {
build.merge(responder.respond_to(req)?);
}
build.status(Status::Unauthorized).ok()
}
}
/// Sets the status of the response to 403 (Forbidden).
///
/// If a responder is supplied, the remainder of th... | Rust | 0 |
coder_problems_backend::s3;
use atcoder_problems_backend::utils::init_log_config;
use serde::Serialize;
use sql_client::accepted_count::AcceptedCountClient;
use sql_client::contest_problem::ContestProblemClient;
use sql_client::language_count::LanguageCountClient;
use sql_client::models::UserSum;
use sql_client::simple... | Rust | 0 |
ION);
if permissions & 7 << 6 != 0 {
assert_ne!(AddAccessAllowedAce(res.as_mut_ptr() as *mut _, ACL_REVISION,
unix_perms_to_windows_access_mask(permissions & 7)
user.storage.as_ptr() as *const _), 0)
}
if permissions & 7... | Rust | 0 |
.len() == 2 => {}
_ => panic!("test failed"),
}
}
}
<gh_stars>1-10
use super::IntegPointData;
use crate::shapes::{op, Scratchpad};
use crate::util::SQRT_2;
use crate::StrError;
use russell_lab::Matrix;
use russell_tensor::Tensor4;
/// Implements the gradient(G) dot 4th-tensor(D) dot gradient(G)... | Rust | 0 |
tors::Pair;
use std::fmt::{Display, Formatter};
use std::path::PathBuf;
use std::str::FromStr;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum NamedValueError {
#[error(
"Named value argument expected a string, but given value `{0}` is not valid (note: \
the value of the string should be wra... | Rust | 0 |
#[allow(clippy::if_same_then_else)]
if pos == trial.len() && rule_idx != self.rule.len() {
return AutoFillResult::Conflict;
} else if let Some(&AutoFillResult::Conflict) = cache.get(&key) {
return AutoFillResult::Conflict;
}
for (a, t)... | Rust | 0 |
:*;
use crate::geometry::{Circle, Polygon};
use crate::math::Vec2;
#[test]
fn test_gjk_poly_poly() {
let mut gjk = GJK::new();
let a = Polygon::new(&vec![
Vec2::new(0.0, 0.0),
Vec2::new(5.0, 0.0),
Vec2::new(5.0, 5.0),
Vec2::new(0.0, 5.0),... | Rust | 0 |
(&dir).unwrap();
let mut file = File::create(&dir.join(format!("{}.md", name))).unwrap();
file.write_all(&contents.as_bytes()).unwrap();
}
/// Disable default features.
fn no_default_features(mut self) -> Self {
self.default_features = false;
self
}
/// Add the spe... | Rust | 0 |
ocess.check_call(
'cp /etc/apt/sources.list.bak /etc/apt/sources.list', shell=True)
except subprocess.CalledProcessError as error_output:
print(
'Copy /etc/apt/sources.list.bak failed: {0}'.format(error_output))
print(
'\033[1;31m\nAll Kali repositories have been deleted... | Python | 1 |
();
// TODO: Look into a functional way of doing this
let mut importer_variants_by_extension = HashMap::new();
for variant in importer_variants.iter() {
for ext in variant.extensions.iter() {
importer_variants_by_extension.insert(*ext, variant.clone());
}
}
let path_cache = CacheRef::<ResourcesCac... | Rust | 0 |
ue.setComponentByName('Cookie', cookie)
else:
control_value.setComponentByName('Cookie', OctetString(''))
return build_control('1.2.840.113556.1.4.841', criticality, control_value)
def extended_dn_control(criticality=False, hex_format=False):
control_value = ExtendedDN()
control_value.setCompo... | Python | 1 |
Send + Sized + 'static {
/// Retrieve some bytes in `column` with `key`.
fn get_bytes(&self, column: &str, key: &[u8]) -> Result<Option<Vec<u8>>, Error>;
/// Store some `value` in `column`, indexed with `key`.
fn put_bytes(&self, column: &str, key: &[u8], value: &[u8]) -> Result<(), Error>;
/// R... | Rust | 0 |
from torch.utils.data import Dataset
import numpy as np
from h5py import File
import scipy.io as sio
from h36m import data_utils
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random
class H36motion3D(Dataset):
def __init__(self, actions='all', input_n=10, output_n=10, split=0,... | Python | 1 |
import pandas as pd
data ={
"Name" :["shipra","vidhi","nikita"],
"Age" :[20,22,19],
"City":["ghaziabad","delhi","noida"]
}
filepath=r"C:\Users\Lenovo\Desktop\pythonws\sample1.xlsx"
df= pd.DataFrame(data)
df.to_csv(filepath )
df = pd.read_csv(filepath)
print(df.head()) | Python | 1 |
-generator/src/writer/rust_native/return_type_wrapper.rs
use maplit::hashmap;
use once_cell::sync::Lazy;
use crate::{
CompiledInterpolation,
ReturnTypeWrapper,
StrExt,
StringExt,
};
use super::RustNativeGeneratedElement;
impl RustNativeGeneratedElement for ReturnTypeWrapper<'_> {
fn element_order(&self) -> u8 {... | Rust | 0 |
son-rpc error code to integer defined in json-rpc spec.
/// Then we have server implementation specific error codes which in case
/// of SPDK are inverted errno values so for example ENOENT becomes
/// -ENOENT jsonrpc error code.
pub fn json_code(&self) -> i32 {
self.code.into()
}
}
impl Rp... | Rust | 0 |
lone,
{
self.0
.deref_mut()
.as_mut_any()
.downcast_mut::<T>()
.ok_or_else(|| context.construct_type_error("cannot downcast `Captures` to given type"))
}
}
/// Boa representation of a Function Object.
///
/// FunctionBody is specific to this interpreter, ... | Rust | 0 |
::Future;
use std::mem;
use zipkin::{Endpoint, Report, Sample, Span, TraceId};
pub fn service_fn<F>(f: F) -> ServiceFn<F> {
ServiceFn(f)
}
pub struct ServiceFn<F>(F);
impl<T, F, I, O> Service<I> for ServiceFn<T>
where
T: Fn(I) -> F,
F: Future<Output = O>,
{
type Response = O;
type Future = F;
... | Rust | 0 |
policy = {
"id": 1,
"entity_id": 1,
"name": "strict",
"description": "Strict Data Policy",
"threshold_privacy": "CLOUD_NOT_IN_EU_BY_US_PROVIDER",
"threshold_latency": 50,
"threshold_accuracy": 60,
"threshold_cost": 40,
"threshold_quality": 60,
... | Python | 1 |
domain: &str, path: &str) -> Option<Arc<CacheItem>> {
self.data
.get(domain)
.map(|x| x.get(path).map(Arc::clone))
.flatten()
}
}
pub enum DataBlock {
CacheBlock {
bytes: Bytes,
compressed: bool,
path: ArcPath,
},
// for use warp
... | Rust | 0 |
"""add_cascade_ondelete
Revision ID: 9b3030cd23b4
Revises: add_resolution_to_stream
Create Date: 2025-09-06 20:37:08.871075
"""
from typing import Sequence, Union
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "9b3030cd23b4"
down_revision: Union[str, None] = "add_resolution_to_strea... | Python | 1 |
/// 1. If `reentrant-hooks` is `true` *or* `KBS2_HOOK` is *not* present in the environment,
/// the hook is run.
/// 2. If `reentrant-hooks` is `false` (the default) *and* `KBS2_HOOK` is already present
/// (indicating that we're already in a hook), nothing is run.
pub fn call_hook(&self, cmd... | Rust | 0 |
# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/common/streamIDs.py
STREAM_ID_CHAT_MIN = 1
STREAM_ID_CHAT_MAX = 99
CHAT_INITIALIZATION_ID = 50
STREAM_ID_AVATAR_BATTLE_RESULTS = 100
STREAM_ID_ACCOUNT_CMDS_MIN = 200
STREAM_ID_ACCOUNT_CMDS_MAX = 30000
class RangeStreamIDCallbacks(object):... | Python | 1 |
'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
... | Rust | 0 |
rollback_greenlet.start()
test_greenlet.join()
self.assertTrue(test_greenlet.successful())
rollback_greenlet.join()
self.assertTrue(rollback_greenlet.successful())
result = test_greenlet.value
self.assertEqual(result, [(test_number, )])
connection_pool.c... | Python | 1 |
unsafe { Pin::new_unchecked(&mut *self.data.get()) }
}
}
// Can be used on tuple structs.
// Can be used together with pin_project.
#[pin_init]
#[pin_project]
struct Pinned<T>(T, #[pin] PhantomPinned);
#[pin_init]
#[pin_project]
struct TwoMutex {
#[pin]
a: Mutex<i32>,
#[pin]
b: Mutex<Pinned<i3... | Rust | 0 |
from queue import LifoQueue as Pila
def cantidad_elementos(pila : Pila) -> int:
#la pila no esta vacia
pilaSecundaria:Pila = Pila()
contador = 0
#Esto trata de contar cada elemento que pasa
while (pila.empty() == False):
tope = pila.get()
contador += 1
pilaSecundaria.pu... | Python | 1 |
from collections.abc import Sequence
from agentdojo.agent_pipeline.base_pipeline_element import BasePipelineElement
from agentdojo.agent_pipeline.tool_execution import tool_result_to_str
from agentdojo.base_tasks import BaseInjectionTask, BaseUserTask
from agentdojo.functions_runtime import EmptyEnv, Env, FunctionsRun... | Python | 1 |
{
config: LoraConfig,
initialized: &'a Initialized,
command_producer: Sender<'a, DriverMutex, CommandBuffer, 2>,
response_consumer: Receiver<'a, DriverMutex, Response, 2>,
}
pub struct Rak811Modem<'a, UART, RESET>
where
UART: AsyncBufRead + AsyncBufReadExt + AsyncWrite + AsyncWriteExt + 'static,
... | Rust | 0 |
nelja_kirjainta = []
viisi_kirjainta = []
kuusi_kirjainta = []
def tarkista(sana: str):
loytyi = False
for kirjain in sana:
if kirjain in "abcdefghijklmnopqrstuvwxyzåäö":
loytyi = True
else:
loytyi = False
break
return loytyi
sanalista = "nykysuomensanal... | Python | 1 |
_end` , the interpreter needs to skip all instructions
//! until it reaches the *matching* `end`. That's quite inefficient compared
//! to a plain goto to the specific position.
//!
//! Because of this, the translation from the Wasm structured stack machine into a
//! plain one is taking place.
//!
//! # Locals
//!
//!... | Rust | 0 |
test_sync.outputs().next().unwrap().typ()
);
Ok(())
}
#[test]
fn test_flatten() -> Result<()> {
let test_iface = interface("a: in Stream<Group<size: Bits<32>, elem: Stream<Bits<32>>>, d=1>")
.unwrap()
.1;
let test_flatten = FlattenStream:... | Rust | 0 |
up Management Menu ===")
print("1. List all groups")
print("2. Add new group")
print("3. Remove group")
print("4. Update group scene")
print("5. Update group Drive folder")
print("6. Update group Record folder")
print("7. Save and exit"... | Python | 1 |
# coding=utf-8
# Copyright 2023 HuggingFace 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 at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | Python | 1 |
validator who's been jailed forever")]
UnjailFromJailForeverForbidden {},
#[error("Jail did not yet expire")]
JailDidNotExpire {},
#[error("Invalid metadata - {data} length must be {min}-{max} characters")]
InvalidMetadata {
data: &'static str,
min: usize,
max: usize,
}... | Rust | 0 |
}
#[inline]
pub fn decode_clear_value(&self, value: ClearValue) -> ClearValue {
let aspects = self.aspects();
if aspects.depth && aspects.stencil {
assert!(matches!(value, ClearValue::DepthStencil(_)));
} else if aspects.depth {
assert!(matches!(value, ClearValu... | Rust | 0 |
from django.urls import path
from . import views
app_name = 'shows'
urlpatterns = [
path('', views.index, name='index'), # /shows
path('new', views.new, name='new'), # /shows/new
path('create', views.create, name='create'), # /shows/create
path('<int:id>', views.show, name='show'), # /shows/<id>
... | Python | 1 |
]
#[should_fail]
fn test_invert_zero() {
Mpq::new().invert();
}
}
#[cfg(test)]
mod test_mpf {
use super::*;
#[test]
#[should_fail]
fn test_div_zero() {
let x = Mpf::new(100);
x / x;
}
}
<filename>adapter/src/error.rs
use std::fmt;
#[derive(Debug)]
pub struct U... | Rust | 0 |
args.module:
# Busca por testes do módulo específico em ambos os diretórios
test_patterns = [
f"tests/unit/test_{args.module}.py",
f"tests/integration/test_{args.module}*.py"
]
found_tests = []
for pattern in test_patterns:
pattern_pa... | Python | 1 |
0, location),
0x4000..=0x7fff => self.rom.value_at(location - 0x4000),
0x8000..=0x9fff => self.video_ram[location - 0x8000],
0xa000..=0xbfff => self.ram.value_at(location - 0xa000),
0xc000..=0xdfff => self.work_ram[location - 0xc000],
0xe000..=0xfdff => self.w... | Rust | 0 |
Widget)>;
}
extern "C" {
pub fn Fl_Tooltip_current_widget() -> *mut libc::c_void;
}
extern "C" {
pub fn Fl_Tooltip_current(arg1: *mut Fl_Widget);
}
extern "C" {
pub fn Fl_Tooltip_font() -> libc::c_int;
}
extern "C" {
pub fn Fl_Tooltip_set_font(i: libc::c_int);
}
extern "C" {
pub fn Fl_Tooltip_font_s... | Rust | 0 |
torch.utils.data.DataLoader(
dataset_test, sampler=sampler_test,
batch_size=args.batch_size,
num_workers=args.num_workers,
pin_memory=args.pin_mem,
drop_last=False
)
print(f"\n\n--Metrics of the network testing on th... | Python | 1 |
# -*- coding: utf-8 -*-
from box import Box
from PySide6 import QtWidgets
from fastflix.encoders.common.setting_panel import SettingPanel
from fastflix.models.encode import GIFSettings
from fastflix.models.fastflix_app import FastFlixApp
class GIF(SettingPanel):
profile_name = "gif"
def __init__(self, paren... | Python | 1 |
'''Questão 3 [2,0 pontos] As Organizações Tabajara resolveram dar um aumento de salário aos seus
colaboradores e lhe contrataram para desenvolver o programa em Python que irá calcular os
reajustes. Faça um programa que solicite ao usuário o salário de um colaborador e, em seguida,
calcule o reajuste segundo o seguinte ... | Python | 1 |
RFC8017 9.2 PCKS1_v1.5 encoding
///
/// Checks (in constant-time) that the provided encoded message matches
///
/// Function has not been checked for constant-time evaluation
pub fn verify(
message: &[u8],
encoded_message: &[u8],
hash: Hash,
) -> Result<Verification, Verification> {
let res = encode(&m... | Rust | 0 |
from mininet.net import Mininet
from mininet.topolib import TreeTopo
from mininet.node import Controller, RemoteController,OVSSwitch
import random
import threading
# Create and start mininet topology
tree_topo = TreeTopo(depth=3, fanout=2)
net = Mininet(topo=tree_topo, controller=RemoteController,switch=OVSSwitch)
ne... | Python | 1 |
:#?}", code)
}
Err(error) => {
let mut buffer = String::new();
error.report(&source, &mut buffer).unwrap();
eprintln!("{}", buffer);
}
}
}
<reponame>aDotInTheVoid/debug3<gh_stars>0
// This is an enourmous pain, because everything in proc_macro2 is
// behin... | Rust | 0 |
"""WeChat image upload implementation."""
from __future__ import annotations
import json
import mimetypes
from pathlib import Path
from typing import Iterable, Sequence
import requests
from src.platforms.base import ContentBundle, MediaUploadResult, MediaUploader
from .api import WeChatApiError
from .credentials i... | Python | 1 |
!self.kb.is_constant(v) =>
{
match self.singletons.entry(v.clone()) {
Entry::Occupied(mut o) => {
o.insert(None);
}
Entry::Vacant(v) => {
v.insert(Some(t.clone()));
... | Rust | 0 |
from flask import Flask, render_template, request
import pandas as pd
# Load the dataset
df = pd.read_csv("keywords_recipes.csv")
app = Flask(__name__)
def match_recipes(user_input):
user_ingredients = [i.strip().lower() for i in user_input.split(",")]
def score(row):
all_text = f"{row['Keywords']} ... | Python | 1 |
gory = CategorySerializer(read_only=True)
category_id = serializers.PrimaryKeyRelatedField(
source='category',
queryset=Category.objects.all(),
write_only=True,
required=False,
help_text="ID категории для обновления"
)
rating_avg = serializers.FloatField(read_only=Tru... | Python | 1 |
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master... | Python | 1 |
pub fn build(self) -> crate::model::BatchDescribeTypeConfigurationsError {
crate::model::BatchDescribeTypeConfigurationsError {
error_code: self.error_code,
error_message: self.error_message,
type_configuration_identifier: self.type_configuration_identifier,
... | Rust | 0 |
import numpy as np
import pytest
from monty.serialization import loadfn
from pymatgen.analysis.defects.generators import VacancyGenerator
from pymatgen.analysis.defects.supercells import (
_ase_cubic,
get_closest_sc_mat,
get_matched_structure_mapping,
get_sc_fromstruct,
)
def test_supercells(gan_struc... | Python | 1 |
&mut self.screen_chars[y][x]
}
/// Starting at `x`x`y` and moving to the right, place characters of `text` in the console, with
/// the given `background`/`foreground` colours for all the characters.
pub fn draw_text_at(&mut self, x: usize, y: usize, text: &[u8], background: ConsoleColour, foreground: ConsoleC... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.