text string | label_name string | labels int64 |
|---|---|---|
erify content is on page 5
success = verify_page5_content()
if success:
# Create enhanced demo
demo_file = create_final_demo()
print(f"\n" + "="*60)
print("🎉 SECTION 5 SUCCESS!")
print("="*60)
print(f"✅ Section 5 is now correctly positioned on page ... | Python | 1 |
nfig_file.model.generator.encoder_lstm,
# config_decoder_lstm=config_file.model.generator.decoder_lstm,
# config_mhsa=config_file.model.generator.mhsa,
# current_cuda=current_cuda)
# print("Only trainable parameters: ", utils.count_parameter... | Python | 1 |
(&self) -> &bool {
&self.on_ground
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct PlayerLook {
yaw: f32,
pitch: f32,
on_ground: bool,
}
impl PlayerLook {
const PACKET_ID: i32 = 18;
/// Deserializes a Read type into a packet. You usually won't need to use this.
pub fn deserialize... | Rust | 0 |
to
///
/// ```ignore
/// // ...
///
/// let s = match a {
/// A { .. } => "A",
/// B { .. } => "B"
/// };
/// ```
macro_rules! match_variant_name {
(match ($e:expr) { $($v:ident),* $(,)? }) => {
match $e {
$(
$v { .. } => stringify!($v)
),*
}
};
}
/// Syntax sugar for initializing an `ActionLi... | Rust | 0 |
oding
:param model: Transformer Model
:param enc_input: The encoder input
:param start_symbol: The start symbol. In this example it is 'S' which corresponds to index 4
:return: The target input
"""
enc_outputs, enc_self_attns = model.encoder(enc_input)
dec_input = torch.zeros(1, 5).type_as(e... | Python | 1 |
#!/usr/bin/env python3
#
# Copyright (c) 2024-2025, Honda Research Institute Europe GmbH
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notic... | Python | 1 |
SAVE_FIG_FORMAT = 'pgf' # pdf or pgf | Python | 1 |
from __future__ import absolute_import, division, print_function
from gltbx import gl
class display_lists_owner:
def __init__(self, range_values):
self.range_values = range_values
self.list = gl.glGenLists(range_values)
def __del__(self):
try: gl.glDeleteLists(self.list, self.range_values)
excep... | Python | 1 |
[test]
fn resumable_extend() {
let s = "a b c";
// This iterator yields: (Some('a'), None, Some('b'), None, Some('c')), None
let it = s
.chars()
.scan(0, |_, ch| if ch.is_whitespace() { None } else { Some(ch) });
let mut v: SmallVec<[char; 4]> = SmallVec::new();
v.extend(it);
ass... | Rust | 0 |
C=C=C=C=C=C=C=C=C=C=C=C=C=C=C|\n",
4,
);
}
#[test]
fn test_three_note_bar_in_3_4_time() {
let source = "voice A {} play A { :| C C C | }";
write_bars_test(source, "L:1/4\n=C=C=C|\n", 3);
}
#[test]
fn test_triplet_in_4_4_time() {
let source = "voice A... | Rust | 0 |
ok = self.find(txt, flags)
self.searchStringFound.emit(ok)
def keyPressEvent(self, evt):
"""
Protected method handling key press events.
@param evt key press event (QKeyEvent)
"""
if evt.modifiers() == Qt.ControlModifier:
if evt.ke... | Python | 1 |
from prowler.lib.check.models import Check, Check_Report_Kubernetes
from prowler.providers.kubernetes.services.kubelet.kubelet_client import kubelet_client
class kubelet_disable_anonymous_auth(Check):
def execute(self) -> Check_Report_Kubernetes:
findings = []
for cm in kubelet_client.kubelet_conf... | Python | 1 |
.is_match(c),
Entry::EyeColor(c) => ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"].contains(c),
Entry::PassportId(i) => PASSPORT_ID_REGEX.is_match(i),
Entry::CountryId => true,
}
}
}
impl<'a> Passport<'a> {
fn parse(batch: &'a str, re: &Regex) -> Passport<'a> {
... | Rust | 0 |
# Generated by Django 5.1.3 on 2024-12-22 03:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('surveys', '0002_alter_survey_end_date'),
]
operations = [
migrations.RemoveField(
model_name='survey',
name='end_date',
... | Python | 1 |
from unittest import TestCase
from unittest.mock import patch
from webapp.app import create_app
from webapp.authentication import get_publishergw_authorization_header
class TestEndpoints(TestCase):
def _log_in(self, client):
test_macaroon = "test_macaroon"
with client.session_transaction() as s:
... | Python | 1 |
#連結至index.html,然後從py傳訊息過去,以及在html寫py
from flask import Flask, redirect, url_for, render_template
app = Flask(__name__)
@app.route("/<name>")
def home(name):
return render_template("day_02.html", content = name, a = 12345) #傳一些簡單的小東西
if __name__ == "__main__":
app.run(debug=True)
| Python | 1 |
terator<Item = (SomethingSomethingSomethingLongType<D>)>
+ ExactSizeIterator
+ 'a;
}
use std::fs;
use gccjit::OutputKind;
use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
use rustc_codegen_ssa::back::write::{CodegenContext, EmitObj, ModuleConfig};
use rustc_errors::Handler;
use rustc_session::co... | Rust | 0 |
)
{
return Err(anyhow!("Coded width not within constraint bounds."));
}
if coded_height < constraints.min_coded_height
|| (constraints.max_coded_height > 0 && coded_height > constraints.max_coded_height)
{
return Err(anyhow!("Coded height not within constraint bounds."));
}
... | Rust | 0 |
one(&["file", "listen"])
.conflicts_with("file")
.conflicts_with("listen"),
)
.arg(
Arg::with_name("kiss")
.help("Enable KISS framing")
.short("k"),
)
.get_matches();
let bus = args.value_of("bus").unwrap();... | Rust | 0 |
);
err(
"class Foo fun f[T: Foo]() {}",
pos(1, 20),
SemError::BoundExpected,
);
ok("trait Foo {} fun f[T: Foo]() {}");
err(
"trait Foo {}
fun f[T: Foo + Foo]() { }",
pos(2, 19),
SemError::DuplicateTrait... | Rust | 0 |
import cocotb
from cocotb.triggers import First, RisingEdge, Timer
async def wait_edge(dut):
# this trigger never fires
await First(RisingEdge(dut.stream_out_ready))
@cocotb.test()
async def test1(dut):
cocotb.start_soon(wait_edge(dut))
await Timer(10, "ns")
test2 = test1
| Python | 1 |
dedIter::new(
// Move left to encompass all the used data
&cdeffed.go_left(left_uniques),
&deblocked.go_left(left_uniques),
// since r2 uses every other row, we need an extra row if stripe_h is odd
stripe_h + (stripe_h & 1),
crop_h,
)
.map(|row: &[T]| {
HorzPaddedIter::new(
// Limi... | Rust | 0 |
from typing import Any
from litestar import Litestar, get
from litestar.connection import ASGIConnection
from litestar.logging.config import LoggingConfig
from litestar.testing import RequestFactory
from litestar.types.empty import Empty
from litestar.utils.scope.state import ScopeState
def test_connection_base_prop... | Python | 1 |
e);
let mut duration_timeout: u64 = time::future(0xffff_ffff);
// Used to signify the first run through the fuzz run. Used to signal when
// to spin up the other cores on the system.
let mut first_run = true;
let mut dry_run = true;
let last_user_rip = 0;
loop {
if cpu::is_bs... | Rust | 0 |
be an Action::Snapshot")
}
}
}
// Copyright 2022 pyke.io
// 2019-2021 Tauri Programme within The Commons Conservancy
// [https://tauri.studio/]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the Lice... | Rust | 0 |
! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l t... | Python | 1 |
}
}
#[allow(dead_code)]
pub fn parse_to_json(self) -> Result<JsonValue,&'static str>{
match parse(&self.message){
Ok(m)=>{
return Ok(m);
},
Err(_)=>{
return Err("failed-parse_str_to_json");
}
}
}
}
lazy_stat... | Rust | 0 |
from copy import deepcopy
import torch
import torch.distributed as dist
from _utils import split_2d, split_layernorm_2d, split_bias_2d, gather_2d
from oslo.torch.distributed import ParallelContext, ParallelMode
from oslo.torch.nn import LayerNorm2D
tp_size = 4
parallel_context = ParallelContext.from_torch(
data... | Python | 1 |
d_mask = dilation(combined_mask.detach().numpy(), square(20)) # modificare il valore di square per ampliare la maschera
contours_gray_new = find_contours(dilated_mask, 0.8) #nuovi contorni
#contours_gray_new = find_contours(combined_mask.detach().numpy(), 0.8)
contours_gray_new = sorted(contours_gray_new,k... | Python | 1 |
: &'static str = "canmount";
const NAME_CSTR: &'static ::std::ffi::CStr = ::cstr::cstr!("canmount");
const COLUMN_NAME: &'static str = "CANMOUNT";
const RIGHT_ALIGN: bool = true;
const HIDDEN: bool = false;
const READ_ONLY: bool = false;
const SET_ONCE: bool = false;
}
impl Property for Canmount... | Rust | 0 |
# Copyright Materialize, Inc. and contributors. All rights reserved.
#
# Use of this software is governed by the Business Source License
# included in the LICENSE file at the root of this repository.
#
# As of the Change Date specified in that file, in accordance with
# the Business Source License, use of this software... | Python | 1 |
import requests
import geocoder
def get_location(ip_address):
try:
response = requests.get(f'https://ipapi.co/{ip_address}/json/').json()
latitude = response['latitude']
longitude = response['longitude']
city = response['city']
region = response['region']
country = r... | Python | 1 |
# This program gets information and reports login name to the user.
# It also takes the password from the user and validates it.
import login # reminder of how to use modules!
def main():
# Get login name
first = input('Enter your first name: ')
last = input('Enter your last name: ')
idnumber = input(... | Python | 1 |
excellent.",
"This image is rated high for beauty.",
"The aesthetic quality of this image is impressive.",
"This photo has a top aesthetic score.",
"The visual appeal of this image is outstanding.",
]
def add_aesthetic_notice_video(caption, aesthetic_score):
if aesthetic_score <= 4.25:
... | Python | 1 |
o create one")
}
}
}
}
use crate::errors::*;
use clap::ArgMatches;
use error_chain::quick_main;
use getch::Getch;
use i3ipc::I3Connection;
use i3nator::{configfiles::ConfigFile, layouts::Layout, projects::Project};
use lazy_static::lazy_static;
use std::{
convert::Into,
env,
ffi::{O... | Rust | 0 |
ord = use_coord
# self.n_samples = len(self.labels)
# self.img_size = 28
# self.node_gt_att_threshold = node_gt_att_threshold
# print('loading the %s set...' % self.split.upper())
# self.edge_indices, self.xs, self.edge_attrs, self.node_gt_atts, self.edge_gt_atts = [], [], [], [... | Python | 1 |
import io
import matplotlib.pyplot as plt
from flask import session, flash, redirect, url_for, send_file
plt.rcParams['font.family'] = 'DejaVu Sans' # This font is known to support a wide range of Unicode glyphs
class Piechart:
def __init__(self, expenses):
# Filter out any expenses that are zero or negat... | Python | 1 |
# absences/forms.py
from django import forms
from classes.models import Classe
class ClasseSequenceSelectionForm(forms.Form):
classe = forms.ModelChoiceField(queryset=Classe.objects.all(), label="Sélectionner une classe")
sequence = forms.ChoiceField(choices=[('Seq1', 'Séquence 1'), ('Seq2', 'Séquence 2'),('Se... | Python | 1 |
from typing import List, Union
from dataclasses import dataclass
# Assume AslQueryCondition is an abstract base class or interface
class AslQueryCondition:
def with_provider(self, provider: 'AslQuery') -> 'AslQueryCondition':
raise NotImplementedError
@dataclass
class AslQuery:
# Define properties and... | Python | 1 |
2018-2019 the Deno authors. All rights reserved. MIT license.
use atty;
use crate::flags::DenoFlags;
use ansi_term::Style;
use crate::errors::permission_denied;
use crate::errors::DenoResult;
use std::fmt;
use std::io;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
/// Tri-state val... | Rust | 0 |
iter_save_best = 2
else:
iter_save_best = 4
if iter==iter_save_best:
INCV_save_best = False
##################################################################################################################################
""" Save INCV results """
INCV_results ... | Python | 1 |
import logging
from crewai import Agent, Task, Crew, Process
from langchain.agents import Tool
from langchain_experimental.utilities import PythonREPL
from langchain_community.tools import DuckDuckGoSearchRun
from langchain_groq import ChatGroq
import os
os.environ["OPENAI_API_KEY"] = "Your_api"
llm = ChatGroq(temper... | Python | 1 |
def outer(name):
def inner():
print(f"Hello, {name}!")
return inner | Python | 1 |
set_reversed_m128(zero: f32, one: f32, two: f32, three: f32) -> m128 {
m128(unsafe { _mm_setr_ps(zero, one, two, three) })
}
/// All lanes zero.
/// ```
/// # use safe_arch::*;
/// let a = zeroed_m128().to_array();
/// assert_eq!(a, [0.0, 0.0, 0.0, 0.0]);
/// ```
#[must_use]
#[inline(always)]
#[cfg_attr(docs_rs, do... | Rust | 0 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-12-04 05:32
from __future__ import unicode_literals
import numpy as np
from django.db import migrations, models
def populate_userinfos2(apps, schema_editor):
UserInfo2 = apps.get_model("test_models", "UserInfo2")
# Use a fixed seed for generate co... | Python | 1 |
")
@basic_auth.required
def close_gate():
log_action("Zamykanie bramy")
GPIO.output(close_gate_pin, GPIO.HIGH)
time.sleep(2)
GPIO.output(close_gate_pin, GPIO.LOW)
return "Zamykanie bramy"
@app.route("/answer_call")
@basic_auth.required
def answer_call():
log_action("Rozpoczęto połączenie")
... | Python | 1 |
> {
let funcs_js: Handle<JsArray> = JsArray::new(cx, funcs.len() as u32);
for (i, func) in funcs.iter().enumerate() {
let func_js: Handle<JsObject> = function_cov_to_js(cx, func)?;
funcs_js.set(cx, i as u32, func_js)?;
}
Ok(funcs_js)
}
fn function_cov_to_js<'a, C: Context<'a>>(cx: &mut C, func: &Functi... | Rust | 0 |
n_origin = main.get_origin_mm(scale)
main_size = main.get_size_mm(scale)
bottom = gap.bottom_shape
bottom_origin = bottom.get_origin_mm(scale)
bottom_size = bottom.get_size_mm(scale)
for b in range(gap.bites_count):
bite... | Python | 1 |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'form.ui'
##
## Created by: Qt User Interface Compiler version 6.6.3
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
######################... | Python | 1 |
>
pub fn set_role(mut self, input: std::option::Option<crate::model::RoleType>) -> Self {
self.role = input;
self
}
/// Consumes the builder and constructs a [`SharePrincipal`](crate::model::SharePrincipal)
pub fn build(self) -> crate::model::SharePrincipal {
... | Rust | 0 |
xcb_glx_get_clip_plane_reply_t {
sym!(self, xcb_glx_get_clip_plane_reply)(c, cookie, e)
}
/// Returns `true` iff the symbol `xcb_glx_get_clip_plane_reply` could be loaded.
#[cfg(feature = "has_symbol")]
pub fn has_xcb_glx_get_clip_plane_reply(&self) -> bool {
has_sym!(self, xcb_glx_get... | Rust | 0 |
import os
import time
import hashlib
from flask import Flask, render_template, request, redirect, url_for, session, abort, make_response
app = Flask(__name__)
app.secret_key = os.environ.get("SECRET_KEY", "dev-secret-key-change-me")
# --- Flag remains dynamic via GZCTF ---
FLAG = os.environ.get("GZCTF_FLAG", "flag{LO... | Python | 1 |
_string_or_struct, serialize_string},
},
DnsNameServer,
SubConfigPath,
};
use tari_utilities::hex::Hex;
pub use trust_dns_client::rr::dnssec::TrustAnchor;
use crate::auto_update::{dns::UpdateSpec, signature::SignedMessageVerifier};
const LOG_TARGET: &str = "p2p::auto_update";
#[derive(Debug, Clone, Seria... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sqlalchemy import String
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.postgresql import TEXT
from sqlalchemy.orm import Mapped, mapped_column, relationship
from backend.app.admin.model.m2m import sys_role_data_rule, sys_role_menu, sys_user_... | Python | 1 |
hammer.forward = false;
hammer.forward_timer.reset();
hammer.back_timer.reset();
}
} else {
hammer.back_timer.tick(time.delta());
new_pos = hammer
.start
.lerp(hammer.end, hammer.back_timer.percent_left());... | Rust | 0 |
([0.0] * len(libraries))
for idx, lib in enumerate(libraries):
calls = 0
dll = "%s.dll" % lib
if lib in imports:
calls = len(imports[lib])
elif dll in imports:
calls = len(imports[dll])
libs[idx] += calls
tot = libs.sum()
return ( libs / tot ... | Python | 1 |
t(), size=src.shape[-2:]).to(torch.bool)[0]
src_list.append(src)
mask_list.append(mask)
pos_list = [self.position_encoding(src, mask) for src, mask in zip(src_list, mask_list)]
query_embeds = self.query_embed.weight
# Transformer forward
hs, init_reference... | Python | 1 |
class Solution:
def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:
kMod = 1_000_000_007
dirs = [1, 0, -1, 0, 1]
ans = 0
# dp[i][j] := # of paths to move the ball (i, j) out of bound
dp = [[0] * n for _ in range(m)]
dp[startRow][startColumn] = 1
for ... | Python | 1 |
]
pub fn unix_leap_time(&self) -> i64 {
self.unix_leap_time
}
/// Returns leap second correction
#[cfg_attr(feature = "const", const_fn::const_fn)]
pub fn correction(&self) -> i32 {
self.correction
}
}
/// ASCII-encoded fixed-capacity string, used for storing time zone designat... | Rust | 0 |
s = np.ones((5, 6))
point = np.array([2.21, 3.12])
for d in points:
d.flags.writeable = False
values.flags.writeable = False
point.flags.writeable = False
interpn(points, values, point)
RegularGridInterpolator(points, values)(point)
def test_non_c_contigu... | Python | 1 |
pond(f"Custom caption set to: {custom_caption}")
elif session_type == 'setreplacement':
match = re.match(r"'(.+)' '(.+)'", event.text)
if not match:
await event.respond("Usage: 'WORD(s)' 'REPLACEWORD'")
else:
word, replace_word = match.groups(... | Python | 1 |
#!/usr/bin/env python3
from utils.all import *
advent.setup(2020, 17)
fin = advent.get_input()
TESTPLZ = any(a.lower() == 'test' for a in sys.argv[1:])
ftest = io.StringIO('''\
.#.
..#
###
''')
if TESTPLZ:
fin = ftest
timer_start()
startgrid = read_char_matrix(fin)
cube = defaultdict(lambda: '.')
for x, row in en... | Python | 1 |
import train_keras
from keras.models import load_model
import os
import numpy as np
import pandas as pd
from tqdm import tqdm
from keras.callbacks import ModelCheckpoint
import sys
TF_CPP_MIN_LOG_LEVEL=2
TEST_BATCH = 128
def load_params():
X_test = os.listdir('./test-jpg')
X_test = [fn.replace('.jpg', '') for... | Python | 1 |
=> println!("Deleted({}): Title: {}", Meta::name(&b), b.spec.title),
_ => (), // Ignore Restarted (We already use list)
};
}
}
<filename>ghauto-console/src/utils.rs
pub fn pick_repo<'a>(args: &'a Vec<Vec<&'a str>>) -> Option<(&'a str, &'a str)> {
for v in args {
if v[0] == "REPO" {
... | Rust | 0 |
n SDK for Opsgenie REST API
*
* Python SDK for Opsgenie REST API
*
* The version of the OpenAPI document: 2.0.0
* Contact: <EMAIL>
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AccountPlan {
#[serde(rename = "maxUserCount", skip_se... | Rust | 0 |
};
use uuid::Uuid;
/// Represent a single operation from a incoming request until a response is
/// produced
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd, Default)]
pub struct OperationId(Uuid);
impl OperationId {
pub fn new() -> OperationId {
OperationId(Uuid... | Rust | 0 |
import pickle
import numpy as np
import torch
import argparse
from isaaclab.utils.math import quat_mul, quat_conjugate, axis_angle_from_quat
from scipy.spatial.transform import Rotation
def convert_pkl_to_custom(input_pkl, output_txt, fps):
dt = 1.0 / fps
with open(input_pkl, "rb") as f:
motion_dat... | Python | 1 |
import os
from collections import defaultdict
with open(os.path.join(os.path.dirname(__file__), 'input.txt')) as f:
program = [int(x) for x in f.read().split(",")]
class VM:
def __init__(self, program):
self.pointer = 0
self.program = defaultdict(int, enumerate(program))
self.input = ... | Python | 1 |
.build(ctx, "close", hotkey(Key::Escape))
.align_right(),
]),
format!("{} unreachable lanes", num_unreachable).draw_text(ctx),
legend,
])
.padding(16)
.bg(app.cs.panel_bg),
... | Rust | 0 |
anLogger {
pub fn init() {
log::set_logger(&GLOBAL_LOGGER)
.map(|()| log::set_max_level(LevelFilter::Info))
.unwrap();
}
}
impl Log for ThreadLocalScanLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() == Level::Error
}
fn log(&self, ... | Rust | 0 |
[
arr[0][(i, j)].inlined_clone(),
arr[1][(i, j)].inlined_clone(),
]
.into()
})
}
}
impl<N: Scalar + PrimitiveSimdValue, R: Dim, C: Dim> From<[MatrixMN<N::Element, R, C>; 4]>
for MatrixMN<N, R, C>
where
N: From<[<N as SimdValue>::Element; 4]>,
... | Rust | 0 |
class Animal:
def speak(self):
print("I can speak!")
class Dog(Animal):
def bark(self):
print("Woof!")
dog = Dog()
dog.speak()
dog.bark() | Python | 1 |
[inline] fn wrapping_sub(self, other: Self) -> Self { <$t>::wrapping_sub(self, other) }
#[inline] fn wrapping_mul(self, other: Self) -> Self { <$t>::wrapping_mul(self, other) }
}) *
}
}
impl_int! { u8, u16, u32, u64, u128 }
/// LCG iteration is state <- state * m + p.
/// Returns the (m, p) pair that i... | Rust | 0 |
rame_offset);
Ok(Mapping {
map_base,
len: len + frame_offset,
slice_base,
slice_max_len: len,
})
}
/// Copy a slice of bytes from the physical address space into `dst`
pub fn copy_into_slice(&self, dst: &mut [u8]) {
assert!(self.slice... | Rust | 0 |
"""
Модуль для проверки прав пользователя на основе ролей.
"""
from database.models.users import UserModel
from fastapi import Depends, HTTPException, status
from web_api.dependencies.users_auth import get_user
from database.tools.role_rules import RoleRuleTool
from database.models.role_rules import RoleRuleModel
def... | Python | 1 |
---------------------------
// IMPORTS
// ------------------------------------------------------------------------------------------------
use std::collections::VecDeque;
use crate::Layer;
// ------------------------------------------------------------------------------------------------
// TRAITS
// ---------------... | Rust | 0 |
ambda ll: (float(ll[0]), float(ll[1])) if ll is not None else None, r)
),
"HGETALL": lambda r: r and pairs_to_dict(r) or {},
"MEMORY STATS": parse_memory_stats,
"MODULE LIST": lambda r: [pairs_to_dict(m) for m in r],
"RESET": str_if_bytes,
"SENTINEL MASTER": parse_sentinel_master,
"SENTINEL ... | Python | 1 |
# -*- coding: utf-8 -*-
import csv
import matplotlib.pyplot as plt
# Nome do arquivo CSV
# Corrija o caminho PATH para o seu diretorio
arquivo = "PATH/Caixeiro-viajante/data/coords.csv"
# Coordenadas das cidades (armazenadas em uma lista de dicionários)
cidades = []
# Leitura do arquivo CSV e armazenamento das coor... | Python | 1 |
]), FONT(16, bold=False), max_width=200, fg=fg, bg=bg, beard_line=True),
], bg=bg, padding=2).pad(5, bg)
def flag(column):
flag = Image.from_url_with_cache(atlas.flag[table.columns[column]]).to_rgba()
flag = flag.resize_fixed_aspect(height=130) if flag.width / flag.height < 1.3 el... | Python | 1 |
rtic::cyccnt::U32Ext as _;
#[cfg(all(feature = "stm32f4xx", feature = "mpu"))]
use cortex_mpu::{
cortex_m4::{MemoryAttributes, Region},
AccessPermission, ArrayVec,
};
use cortex_m_rt::exception;
use embedded_hal::timer::Periodic;
#[cfg(feature = "wait")]
use embedded_hal::digital::v2::InputPin;
use rtt_log... | Rust | 0 |
([-1, -1, 1], [ 1, -1, 1]),
([-1, 1, 1], [ 1, 1, 1]),
([-1, 1, 1], [-1, -1, 1]),
([ 1, 1, 1], [ 1, -1, 1]),
// Back
([-1, -1, -1], [ 1, -1, -1]),
([-1, 1, -1], [ 1, 1, -1]),
([-1, 1, -1], [-1, -1, -1]),
([ 1, 1, -1], [ 1, -1, -1]),
// Sides
([-1, -1, -1], [... | Rust | 0 |
=> {
match args[i] {
Address(_) => (),
_ => {
println!("Position {} must be an address on line {}", i, env.line_num+1);
exit(0);
},
}
}
_ => ()
}
... | Rust | 0 |
le_name]
async with async_playwright() as playwright:
user_data_path = USER_DATA_PATH / profile_name
proxy_config = None
if profile.proxy:
proxy_config = {
'server': f'{profile.proxy.server}:{profile.proxy.port}',
... | Python | 1 |
Patch a webhook to add a secret."""
patch_data = [{"op": "replace", "path": "/secret", "value": webhook_secret}]
logger.info(f"Patching webhook {webhook_id} to add secret")
await self.send_api_request(
endpoint=f"webhooks/{webhook_id}", method="PATCH", json_data=patch_data
... | Python | 1 |
Args:
batch (batch: dict[str, str | torch.Tensor]): Input batch
args: Additional arguments.
kwargs: Additional keyword arguments.
Returns:
STEP_OUTPUT: Dictionary containing the loss value.
"""
del args, kwargs # These variables are not used.
... | Python | 1 |
import unittest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from src.implementations.alchemy_queue import AlchemyQueue, QueueRepository, ItemRepository
from src.implementations.alchemy_queue.models.item_model import AlchemyItemStatus
from src.implementations.alchemy_queue.base import B... | Python | 1 |
} else {
owners.insert(info.owner.id);
}
match http.get_current_user().await {
Ok(bot_id) => (owners, bot_id.id),
Err(why) => panic!("Could not access the bot id: {:?}", why),
}
},
Err(why) => panic!("Could not ac... | Rust | 0 |
import fastapi
from fastapi import APIRouter
import numpy as np
import torch
from sklearn.preprocessing import normalize
from models.rerank import RerankRequest, RerankResponse, ScoredDocument, EmbeddingRerankRequest
router = APIRouter()
@router.post(
"/rerank/text",
response_model=RerankResponse,
tags=[... | Python | 1 |
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x if x != "banana" else "orange" for x in fruits]
print(newlist)
| Python | 1 |
{}{}", &p1, &p2, &p3, &p4, &p5, &p6)
};
let seven =
|_: (),
p1: String,
p2: String,
p3: String,
p4: String,
p5: String,
p6: String,
p7: String| format!("{}{}{}{}{}{}{}", &p1, &p2, &p3, &p4, &p5, &p... | Rust | 0 |
"""
CloseAI related classes
"""
import asyncio
from asyncio import gather
from alive_progress import alive_bar
from time import time
from GalTransl import LOGGER, TRANSLATOR_DEFAULT_ENGINE
from GalTransl.ConfigHelper import CProjectConfig, CProxy
from typing import Optional, Tuple
from random import choice
from asynci... | Python | 1 |
import marimo
__generated_with = "0.15.1"
app = marimo.App(width="medium")
@app.cell
def _():
import jax
import jax.numpy as jnp
import marimo as mo
from gradients import GradientsEval
return (mo,)
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
# Problem 3
In this proble... | Python | 1 |
_str!(
0,
Position::Pos(regexp!(), regexp!(Token::alphabet(), punctuation!(',')), 1),
Position::Pos(Token::alphabet().into(), punctuation!(',').into(), 1)
),
const_str!(", "),
first1,
const_str!(".")
],
cond![] => [
match_substr!(0, Token::alphabet(), -1),
... | Rust | 0 |
; // Remove SID and PID, so just seed value left
Ok(resp)
}
/// Sends the computed key to the ECU.
///
/// If this function is successful, then the ECU has now allows access to security protected memory regions and functions
///
/// ## Parameters
/// * server - The UDS Diagnostic server
/// * key - The computed ke... | Rust | 0 |
SIGNER).");
// AVR signature validation constants.
static IAS_ANCHORS: [webpki::TrustAnchor<'static>; 1] = [
// Derived via webpki::trust_anchor_util::generate_code_for_trust_anchors.
//
// -----BEGIN CERTIFICATE-----
// <KEY>
// <KEY>
// <KEY>
// <KEY>
// <KEY>
// <KEY>
// <KEY... | Rust | 0 |
return bs
class BlockBoundDefinitionListOpMode(BlockBoundDefinitionDispatcher[F]):
@override(BlockBoundDefinitionDispatcher)
def dispatch(self, d: BoundDefinition) -> Optional[Block[F]]:
if isinstance(d, Alias):
return BlockAliasDef(d)
if isinstance(d, Constant):
re... | Python | 1 |
acceptability_ii = (t_cmf_ii_lower <= to) & (to <= t_cmf_ii_upper)
acceptability_iii = (t_cmf_iii_lower <= to) & (to <= t_cmf_iii_upper)
if units.upper() == Units.IP.value:
t_cmf, t_cmf_i_upper, t_cmf_ii_upper, t_cmf_iii_upper = units_converter(
from_units=Units.SI.value.lower(),
... | Python | 1 |
# Create initial mapping
initial_mapping = create_initial_mapping(text_freq, english_freq)
# Find best mapping
best_mapping, best_score = find_best_mapping(encrypted_text, initial_mapping, english_words)
# Decrypt text with best mapping
decrypted_text = decrypt_text(encrypted_text, be... | Python | 1 |
# ruff: noqa:N801
"""Gridfinity standard constants."""
from dataclasses import dataclass
@dataclass
class gridfinity_standard:
"""Gridfinity standard constants."""
@dataclass
class stacking_lip:
"""Stacking lip constants."""
height_1 = 0.7
height_2 = 1.8
height_3_bin = 1... | Python | 1 |
div>
<div style="background: linear-gradient(135deg, #FFF3E0, #FFE0B2); border: 1px solid #FFCC02; border-radius: 8px; padding: 15px; border-left: 4px solid #FF9800;">
<h4 style="color: #E65100;">🐛 害虫诊断</h4>
<p style="color: #EF6C00;">• 上传害虫照片进行识别<br>• 支持粘虫、玉米螟、蓟... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.