text string | label_name string | labels int64 |
|---|---|---|
name = utils::new_c_string("dither")?;
let bitdepth_in: i32 = pngsave_buffer_options.bitdepth;
let bitdepth_in_name = utils::new_c_string("bitdepth")?;
let strip_in: i32 = if pngsave_buffer_options.strip { 1 } else { 0 };
let strip_in_name = utils::new_c_string("strip")?;
let ... | Rust | 0 |
::one();
DensePolynomial::from_coefficients_vec(coeffs)
}
}
impl<F: PrimeField> Mul<&DensePolynomial<F>> for VanishingPoly<F> {
type Output = DensePolynomial<F>;
fn mul(self, rhs: &DensePolynomial<F>) -> DensePolynomial<F> {
// (x^|H| - b^|H|) * f(x) = x^|H| * f(x) - b^|H| * f(x)
l... | Rust | 0 |
tc = int(input())
for _ in range(tc):
x,y,z = list(map(int, input().split()))
wall = x*y
paint = z/2
import math
print(int(math.floor(paint/wall)))
| Python | 1 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
from langchain_community.callbacks.comet_ml_callback import (
CometCallbackHandler,
)
__all__ = [
"CometCallbackHandler",
]
| Python | 1 |
al()
.child(status::status_layout_factory())
.child(status::usage_layout_factory()),
)
.child(
LinearLayout::horizontal()
.child(
LinearLayout::vertical()
... | Rust | 0 |
SFP_LOM_OEM1: u32 = 0x8976;
pub const IXGBE_SUBDEV_ID_82599_SFP_LOM_OEM2: u32 = 0x06EE;
pub const IXGBE_DEV_ID_82599_BACKPLANE_FCOE: u32 = 0x152A;
pub const IXGBE_DEV_ID_82599_SFP_FCOE: u32 = 0x1529;
pub const IXGBE_DEV_ID_82599... | Rust | 0 |
fa,
populating: usize,
mut current: usize,
input: u8,
) -> usize {
loop {
if current < populating {
return dfa.next_state(current, input);
}
let next = nfa.next_state(current, input);
if next != FAIL_ID {
return next;
}
current = nf... | Rust | 0 |
import re
import logging
from aiogram import F, Router, types
from aiogram.fsm.context import FSMContext
from services.repository import Repository
from services.fragment_sender import FragmentSender
from services.profit_calculator import ProfitCalculator
from keyboards import user_kb
from states.user import BuyPremiu... | Python | 1 |
_1103_distribute_candies_to_people;
//
mod _1108_defanging_an_ip_address;
//
mod _1118_number_of_days_in_a_month;
//
mod _1119_remove_vowels_from_a_string;
//
mod _1122_relative_sort_array;
//
mod _1128_number_of_equivalent_domino_pairs;
//
mod _1133_largest_unique_number;
//
mod _1134_armstrong_number;
//
mod _1137_n... | Rust | 0 |
import numpy as np
from scipy.fft import fft, ifft, fftshift, ifftshift
import matplotlib.pyplot as plt
import pandas as pd
if __name__ == "__main__":
t = 0.01
window_size = int(1000*1000*10 * t)
sample_freq = 10000000
total_t = 1
total_point = total_t * sample_freq
resolution = sample_freq/... | Python | 1 |
(&idx_path).unwrap();
let idx_size = f.metadata().unwrap().len();
let mut orig_idx = IDX::from_file(&f).unwrap();
let mut buffer: Vec<u8> = Vec::new();
buffer.resize(idx_size as usize, 0u8);
let mut cursor = Cursor::new(buffer);
orig_idx.write(&mut cursor).unwrap();
// Load again to chec... | Rust | 0 |
raph_analysis']['basic_blocks_identified']} blocks")
print(f" Register Allocation: {contrib['dynamic_programming']['variables_allocated']} variables")
print(f" Dead Code Elimination: {contrib['pattern_matching']['dead_code_eliminated']} statements")
print(f" Constant Folding: {contrib['patter... | Python | 1 |
# # Koko eating bananas
# # Using binary search algo
def check(bananas, mid_val, H):
time = 0
for i in range(len(bananas)):
# in case of a remainder
if (bananas[i] % mid_val != 0):
time += bananas[i] // mid_val + 1
else:
time += bananas[i] // mid_val
# check ... | Python | 1 |
ol]) # add z-score column
cod = cod[cod[f"z_{col}"].abs() <= thresh] # filter rows
return cod
# cod["z_gross"]=Z_factor(col)
# cod=cod[cod["z_gross"].abs()<=3]
# return cod
if __name__ == "__main__":
cod=pd.read_csv("expanded_data.csv")
threshold=2.5
cod=removing_outliers(... | Python | 1 |
import subprocess
import sys
import os
import platform
def install_dependencies():
print("🚀 Setting up Integrated AI Assistant...")
# Check Python version
if sys.version_info < (3, 8):
print("❌ Python 3.8+ is required. Please upgrade.")
sys.exit(1)
# Determine pip command
... | Python | 1 |
class EndTreatmentType(ElementType,IDisposable):
""" An end treatment type object that is used to hold information about the end treatment applied to bars that are connected to a coupler. """
@staticmethod
def Create(doc,strTreatment=None):
"""
Create(doc: Document) -> EndTreatmentType
Creates a new EndT... | Python | 1 |
{
Red, // unit-like struct
Green,
Blue,
RgbColor(u8, u8, u8), // tuple struct
CmykColor {
cyan: u8,
magenta: u8,
yellow: u8,
black: u8,
},
}
fn enums() {
let c = Color::CmykColor {
cyan: 0,
magenta: 128,
yellow: 0,
black: 255,... | Rust | 0 |
G>;
Versor<T:AllocVersor, N> *= Rotor<T:AllocEven, N>;
Versor<T:AllocVersor, N> *= Reflector<T:AllocOdd, N>;
Versor<T:AllocVersor, N> *= Versor<T:AllocVersor, N>;
);
//
// One
//
impl<T:AllocEven<N>+AddGroup+Mul<Output=T>+AllRefMul<T,AllOutput=T>+One+PartialEq, N:DimName> One for Rotor<T,N> {
//TODO... | Rust | 0 |
'thead', valign='bottom'))
def depart_thead(self, node):
self.body.append('</thead>\n')
# auxiliary method, called by visit_title()
# "with-subtitle" class, no ARIA roles
def section_title_tags(self, node):
classes = []
h_level = self.section_level + self.initial_header_level -... | Python | 1 |
from .. import IconBase
class IconChevronDown(IconBase):
class_name = "lucide lucide-chevron-down"
svg_data = {
"attrs": {
"width": "24",
"height": "24",
"view_box": "0 0 24 24",
"fill": "none",
"stroke": "currentColor",
"stroke_width": "2",
"stroke_... | Python | 1 |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | Python | 1 |
# Generates an opcode decoder table from the table in opcode_id.tab
#
# Each line of the .tab file defines one bitmask and the corresponding
# instruction. 0/1 means that the bit at the given position must have
# that value, '-' means that the bit can have any value (eg. it's a
# register number or immediate data).
#
#... | Python | 1 |
# Copyright 2024 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 |
ring::Relaxed)
}
}
impl Default for StatCounter {
fn default() -> StatCounter {
StatCounter(std::sync::atomic::AtomicU64::new(0))
}
}
impl std::fmt::Debug for StatCounter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.fetch().fmt(f)
}
}
#[cfg(test)]
mo... | Rust | 0 |
"""
Classifies: CHEBI:76578 diradylglycerol
"""
from rdkit import Chem
def is_diradylglycerol(smiles: str):
"""
Determines if a molecule is a diradylglycerol based on its SMILES string.
A diradylglycerol is a glycerol molecule where two of the three hydroxyl groups
are substituted with acyl (ester-link... | Python | 1 |
import sqlite3
#Lista todos os livros disponiveis
def listar_livros_disponiveis(conn):
query = "SELECT * FROM Livros WHERE id IN (SELECT livro_id FROM Exemplares WHERE estado = 'disponível')"
return conn.execute(query).fetchall()
#Encontra todos os livros emprestados no momento
def listar_livros_emprestados(c... | Python | 1 |
assId::JAVA_LANG_STRING, 0);
pub const JAVA_LANG_REFLECT_FIELD_CLAZZ_FIELD: FieldId = FieldId(ClassId::JAVA_LANG_REFLECT_FIELD, 0);
pub const JAVA_LANG_REFLECT_FIELD_OFFSET_FIELD: FieldId = FieldId(ClassId::JAVA_LANG_REFLECT_FIELD, 1);
pub const JAVA_LANG_REFLECT_FIELD_NAME_FIELD: FieldId = FieldId(ClassId::JAVA_LANG_... | Rust | 0 |
{
PoweredOff,
PoweredOn,
Unauthorized,
Unsupported
}
/// State of Hci interface.
#[derive(Debug, Clone, PartialEq)]
pub enum BtLeAddressType {
Public,
Random,
Unknown
}
#[derive(Debug, Clone, PartialEq)]
/// Data of callback for method le_conn_complete().
pub struct BtLeConnectionComplete... | Rust | 0 |
#!/usr/bin/env python
import baseSchemaClass
from leginon import leginondata
class SchemaUpdate17561(baseSchemaClass.SchemaUpdate):
'''
This schema update converts frame rate to frame time if present
'''
def upgradeLeginonDB(self):
if not self.leginon_dbupgrade.columnExists('CameraEMData', 'frame rate'):
ret... | Python | 1 |
/// Only works when the child is disconnected from the layer tree.
pub fn add_child_end(pseudo_self: Rc<ContainerLayer>, new_child: Layer) {
new_child.with_common(|new_child_common| {
assert!(new_child_common.parent.is_none());
assert!(new_child_common.prev_sibling.is_none());
... | Rust | 0 |
pub fn config_from_cmd() -> Config {
let args = wild::args_os();
let args = argfile::expand_args_from(
args,
argfile::parse_fromfile,
argfile::PREFIX,
).unwrap();
let matches = App::new("LN-Matrix-Bot")
.version("0.1.0")
... | Rust | 0 |
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
def floor():
l = 0
h = n - 1
ans = -1
while l <= h:
mid = (l + h) / 2
... | Python | 1 |
('䴝', "chuài"),
('䴞', "dí"),
('䴟', "huán"),
('䴠', "yǎo"),
('䴡', "lì"),
('䴢', "mí"),
('䴣', "hū"),
('䴤', "shēng"),
('䴥', "jiā"),
('䴦', "yín"),
('䴧', "wēi"),
('䴩', "piáo"),
('䴪', "lù"),
('䴫', "líng"),
('䴬', "yì"),
('䴭', "cái"),
('䴮', "shàn"),
('䴯', "hū"),... | Rust | 0 |
default_display(frame)
print("Displaying 'Hello World!' - Press Ctrl+C to exit...")
# Create tap detection task
tap_task = asyncio.create_task(detect_taps(frame))
# Main loop
while not should_exit:
await asyncio.sleep(... | Python | 1 |
<u32, super::CTRL>;
#[doc = "Register CTRL `reset()`'s with value 0"]
impl crate::ResetValue for super::CTRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "FlexIO Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLEXEN_A {
#[doc = "0: Fl... | Rust | 0 |
import os
import torch
# from colbert.utils.runs import Run
from colbert.utils.utils import print_message, save_checkpoint
from colbert.infra.run import Run
def print_progress(scores):
positive_avg, negative_avg = round(scores[:, 0].mean().item(), 2), round(scores[:, 1].mean().item(), 2)
print("#>>> ", pos... | Python | 1 |
# Copyright 2018 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | Python | 1 |
rror_message(tool_validation['error_type'], tool_validation.get('invalid_tools', []))
mcp_tool_results = [{'tool_name': 'error', 'arguments': {}, 'result': None, 'error': error_msg, 'timestamp': time.time()}]
logger.warning(f"MCP工具验证失败: {error_msg}")
e... | Python | 1 |
Pandoc element
trait ToPandoc {
/// Encode to a Pandoc document
fn to_pandoc(&self, _context: &mut Context) -> pandoc::Pandoc {
pandoc::Pandoc(pandoc::Meta(HashMap::new()), Vec::new())
}
/// Encode to a Pandoc inline element
fn to_pandoc_inline(&self, _context: &mut Context) -> pandoc::Inl... | Rust | 0 |
//K)L
///
///Visually, the above map of orbits looks like this:
///
/// G - H J - K - L
/// / /
///COM - B - C - D - E - F
/// \
/// I
///
///In this visual representation, when two objects are connected by a line, the one on the right directly orbits the one on... | Rust | 0 |
n["id"].as_u64().unwrap();
let block = json["block"].as_bool().unwrap() as c_int;
WEBVIEW_MAP.with(|cell| {
let webview_map = cell.borrow();
if let Some(webview) = webview_map.get(&id) {
let res = unsafe { webview_sys::webview_loop(*webview, block) };
Ok(json!(res))
} else {
Err(any... | Rust | 0 |
PartialEq)]
pub enum PAD11_SR_A {
#[doc = "1: Enables Slew rate control on pad value."]
SR_EN = 1,
}
impl From<PAD11_SR_A> for bool {
#[inline(always)]
fn from(variant: PAD11_SR_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `PAD11_SR`"]
pub type PAD11_SR_R = crate::R<bool, PA... | Rust | 0 |
2, 0.5, 0.7]), "b": 0.2}
got = first_derivative(
lambda params: params["a"] @ params["a"] + 2 * params["b"],
params=params,
bounds=bounds,
min_steps=min_steps,
)
assert np.allclose(got.derivative["a"], np.array([2, 4, 6]))
assert np.allclose(got.derivative["b"], 2)
def... | Python | 1 |
import torch
from torch import Tensor as tensor
import torch.nn as nn
def get_one_hot(y_s: torch.tensor, num_classes: int):
"""
args:
y_s : torch.Tensor of shape [n_task, shot]
returns
y_s : torch.Tensor of shape [n_task, shot, num_classes]
"""
one_hot_size = list(y... | Python | 1 |
"id": "abc123" }).to_string();
let actual = serde_json::to_string(&SolrDeleteRequest::from_id("abc123")).unwrap();
assert_eq!(expect, actual);
let expect = json!({ "id": [ "abc", "123" ] }).to_string();
let actual =
serde_json::to_string(&SolrDeleteRequest::from_ids(vec!["a... | Rust | 0 |
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
extra_compile_flags = {}
gencodes = ['-arch=sm_50',
'-gencode', 'arch=compute_50,code=sm_50',
'-gencode', 'arch=compute_52,code=sm_52',
'-gencode', 'arch=compute_60,code=sm_60',
... | Python | 1 |
| Example:
|
| The following example removes the second entry in the list. Please
| note that the
| list index starts with 1.
|
|
| Dim MyList As Sc... | Python | 1 |
# Copyright (c) 2025, NVIDIA CORPORATION. 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 |
import re
def format_for_google_chat(text):
text = text.replace('<br>', '\n')
text = re.sub(r'\*\*\*(.*?)\*\*\*', r'*_\1_*', text)
text = re.sub(r'\*\*(.*?)\*\*', r'*\1*', text)
text = re.sub(r'\*(.*?)\*', r'_\1_', text)
return text
| Python | 1 |
overflows.
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
/// Increments the first element of an array by 1.
///
/// Takes a mutable reference to and array and returns a reference to the array.
pub fn inc_array(array: &mut [i32]) -> &mut [i32] {
// How does this function guarentee that the passed array will cont... | Rust | 0 |
# src/main.py
###########
# IMPORTS #
###########
from multiprocessing import Process
from scripts.simulations.electromagnetic_simulation import run_elec_simulation
from scripts.simulations.gravity_simulation import init_simulation_state, run_grav_simulation
from scripts.simulations.strong_force_simulation import run_... | Python | 1 |
#!/usr/bin/python3
'''
Implementation of the User class which inherits from BaseModel
'''
from os import getenv
from sqlalchemy import Column, String
from sqlalchemy.orm import relationship
from models.base_model import BaseModel, Base
class User(BaseModel, Base):
'''
Definition of the User class
... | Python | 1 |
/#read--modify--write-api).\n\nFor information about avaliable fields see [mtirqm](mtirqm) module"]
pub type MTIRQM = crate::Reg<u32, _MTIRQM>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MTIRQM;
#[doc = "`read()` method returns [mtirqm::R](mtirqm::R) reader structure"]
impl crate::Readable for MTIRQM {}
#[doc = ... | Rust | 0 |
imeunits));
let loader = Box::new(VcdLoader::new(PathBuf::from(opts.input), cycle_time)?);
let wave = Wave::load(loader/*, &config*/)?;
//let mut interpreter = LuaInterpreter::new(state, wave);
let state = ScriptState {
ui: State::new(&config)?,
wv: wave,
... | Rust | 0 |
715;
pub const ADVENTURE___PINEAPPLE: u16 = 4716;
pub const ADVENTURE___PINEAPPLE_SEED: u16 = 4717;
pub const MYSTERY_DOOR: u16 = 4718;
pub const MYSTERY_DOOR_SEED: u16 = 4719;
pub const ADVENTURE_CHECKPOINT: u16 = 4720;
pub const ADVENTURE_CHECKPOINT_SEED: u16 = 4721;
pub const THE_ADVENTURE_BEGINS: u16 = 4722;
pub co... | Rust | 0 |
from modelos.trabalhoProducao import TrabalhoProducao
class TestTrabalhoProducao:
def testDeveRetornarTrueQuandoEstadoTrabalhoEhZero(self):
trabalhoProducaoTeste = TrabalhoProducao()
trabalhoProducaoTeste.estado = 0
esperado = True
recebido = trabalhoProducaoTeste.ehParaProduzir
... | Python | 1 |
mu: Arc<Mutex<usize>>, alt_mu: Arc<Mutex<usize>>, tx: Sender<()>) {
for _ in 0..ITERATIONS {
select! {
mut count = mu.lock().fuse() => *count += 1,
mut count = alt_mu.lock().fuse() => *count += 1,
}
}
tx.send(())... | Rust | 0 |
# -*- coding: utf-8 -*-
from __future__ import print_function
'''Verification of the rotate method for an 3D elastic section.'''
import geom
import xc
from materials import typical_materials
import math
__author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AOO)"
__copyright__= "Copyright 2015, LCPT and AOO"
__licens... | Python | 1 |
= 54,
FARSI = 55,
FRENCH_BELGIAN = 56,
FRENCH_LUXEMBOURG = 57,
FRENCH_SWISS = 58,
GERMAN_AUSTRIAN = 59,
GERMAN_LUXEMBOURG = 60,
GERMAN_LIECHTENSTEIN = 61,
GERMAN_SWISS = 62,
GREEK = 63,
HEBREW = 64,
HUNGARIAN = 65,
INDONESIAN = 66,
ITALIAN_SWISS = 67,
JAPANESE = 6... | Rust | 0 |
IpAddr
= env::var("QDADDR")
.unwrap_or("0.0.0.0".into())
.parse()
.expect("Expected a valid IP address.");
let addr = (ipaddr, port).into();
let server = Server::bind(&addr)
.serve(|| service_fn(quikdecision))
.map_err(|e| eprintln!("server error: {}... | Rust | 0 |
for $typename<'_, T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.deref().fmt(f)
}
}
}
}
macro_rules! ref_or_box_impls {
($typename:ident) => {
impl<T: ?Sized> Deref for $typename<'_, T> {
type Target = T;
f... | Rust | 0 |
235, 167, 103, 034, 062, 007, 010, 032, 146, 113, 039, 096, 174, 003, 219,
232, 166, 240, 121, 167, 013, 098, 238, 122, 116, 193, 114, 215, 213, 175, 181, 075, 166,
224, 164, 140, 146, 053, 120, 010, 037, 104, 094, 136, 225, 249, 102, 171, 160, 097, 132,
015, 071, 035, 056, 000, 074, 130, 168, ... | Rust | 0 |
_usage = context.get("resource_usage", {})
for resource, usage in resource_usage.items():
if resource not in metrics.resource_usage:
metrics.resource_usage[resource] = usage
else:
old_usage = metrics.resource_usage[resource]
... | Python | 1 |
assert_eq!(
query_ticket_info(deps.as_ref(), String::from(ZERO_MATCH_SEQUENCE))
.unwrap()
.holders,
vec![Addr::unchecked("addr0000")]
);
assert_eq!(
query_ticket_info(deps.as_ref(), String::from(ONE_MATCH_SEQUENCE))
.unwrap()
.holders,
... | Rust | 0 |
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(param_knobs)
.with_default_spacer()
.with_child(track_results)
}
fn params_widget() -> impl Widget<Arc<RecommendationsKnobs>> {
let row = |label| {
Flex::column()
.cross_axis_alignment(CrossAxisAlignment:... | Rust | 0 |
import streamlit as st
from sympy import Symbol, Eq, solve
conversion_factors = {
'🔗 Length': {
'Foot': 0.3048, 'Miles': 1609.34, 'Inch': 0.0254, 'Kilometer': 1000,
'Meter': 1, 'Centimeter': 0.01, 'Millimeter': 0.001,
'Micrometer': 1e-6, 'Nanometer': 1e-9
},
'🌐 Area': {
'S... | Python | 1 |
def _cast_to_config(obj):
if isinstance(obj, dict):
return DictConfig(obj, flags={'allow_objects': True})
return obj
| Python | 1 |
#!/usr/bin/env python2
import sys
import serial
import shm
if len(sys.argv) != 2:
print "Usage: auv-lcd [port]"
sys.exit(1)
port = sys.argv[1]
print "Connecting to LCD on " + port
ser = None
def conn():
global ser
ser = serial.Serial(port=port, baudrate=115200, timeout=1)
conn()
if ser.isOpen():
... | Python | 1 |
1: ::USAGE,
StringIndex: ::USHORT,
Reserved2: ::USHORT,
DesignatorIndex: ::USHORT,
Reserved3: ::USHORT,
DataIndex: ::USHORT,
Reserved4: ::USHORT,
}}
STRUCT!{struct HIDP_VALUE_CAPS {
UsagePage: ::USAGE,
ReportID: ::UCHAR,
IsAlias: ::BOOLEAN,
BitField: ::USHORT,
LinkCollection:... | Rust | 0 |
f._parse_xml_files()
# Заполняем БД
if parsed_data:
# Передаем app для использования контекста БД, если он есть
self._populate_db(parsed_data, app=app)
else:
logging.warning("Парсинг не вернул данных для загрузки в БД.")
# TODO: Улучшить проверку о... | Python | 1 |
# Copyright (c) 2018 Tildes contributors <code@tildes.net>
# SPDX-License-Identifier: AGPL-3.0-or-later
from itertools import product
from tildes.schemas.user import (
is_valid_username,
USERNAME_MAX_LENGTH,
USERNAME_MIN_LENGTH,
)
def test_too_short_invalid():
"""Ensure too-short username is invalid... | Python | 1 |
// discover the root directory of the current git repository
let repo: Repository = Repository::open_from_env().map_err(|e| {
error!("Unable to open a Git repository from the current directory: {}", e);
exit(1)
}).unwrap();
let root: PathBuf = repo.workdir().unwrap_... | Rust | 0 |
from __future__ import annotations
from typing import Dict, List, Optional, Tuple, Union
from .constants.ranks import *
import re
"""
# im gonna leave these here forever
# for future explorers
# to see how life was
def get_xp_to_next_lvl(lvl: int) -> int:
if lvl > 37:
return (lvl - 18) * 500
if lvl... | Python | 1 |
1, argv, 2, 0, "list ?index ...?")?;
if argv.len() != 3 {
lindex_into(&argv[1], &argv[2..])
} else {
lindex_into(&argv[1], &*argv[2].as_list()?)
}
}
pub fn lindex_into(list: &Value, indices: &[Value]) -> MoltResult {
let mut value: Value = list.clone();
for index_val in indices {
... | Rust | 0 |
response = client.chat.completions.create(
model=model_name,
messages=[{"role": "user", "content": prompt}],
temperature=0.5,
timeout=DEFAULT_TIMEOUT # Timeout for the OpenAI API call
)
response = response.choices[0].message.content.strip()
... | Python | 1 |
}
#[doc = "Bit 0 - Stream x clear FIFO error interrupt flag (x = 3..0)"]
#[inline]
pub fn cfeif0(&mut self) -> _CFEIF0W {
_CFEIF0W { w: self }
}
}
use syntax::parse::token;
use syntax::parse::token::Token;
use syntax::parse::token::intern;
pub type Lexer<R> = RustLexer<R>;
rustlex! RustLexer... | Rust | 0 |
r_users_list_continue,
'docs/get_folder_info': docs_get_folder_info,
'docs/list': docs_list,
'docs/list/continue': docs_list_continue,
'docs/permanently_delete': docs_permanently_delete,
'docs/sharing_policy/get': docs_sharing_policy_get,
'docs/sharing_policy/set': docs_sharing_policy_set,
'... | Python | 1 |
otal_loss(valid_data, z_vect_final)
if record_results:
results['valid_loss'].append(valid_loss)
results['train_loss'].append(total_loss(train_data, z_vect_final))
# results['tests_loss'].append(total_loss(tests_data, z_vect_final))
return valid_loss
hyperloss(tra... | Python | 1 |
BitCoord(side.pieces.king.0),
colour,
mbb,
);
let is_in_check = allowed_non_king_moves != BitBoard(0xFF_FF_FF_FF_FF_FF_FF_FF);
// Now get all moves disregarding restrictions.
let mostly_legal_moves = side.pieces.all()
.iter()
.flat_map(|src| {
let pi... | Rust | 0 |
ntextAll<'input>>>
where
Self: Sized,
{
self.child_of_type(0)
}
fn valueBang(&self) -> Option<Rc<ValueBangContextAll<'input>>>
where
Self: Sized,
{
self.child_of_type(0)
}
/// Retrieves first TerminalNode corresponding to token BANG
/// Returns `None` ... | Rust | 0 |
.01;
model.yoff += 0.01;
}
fn view(app: &App, model: &Model, frame: Frame) {
let draw = app.draw();
draw.background().color(WHITE);
draw
.line()
.weight(4.0)
.color(BLACK)
.points(model.anchor, model.mouse);
draw.to_frame(app, &frame).unwrap();
}
<reponame>hekrause/cryptocompare<filename>e... | Rust | 0 |
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import numpy as np
'''一:打开显示保存'''
# img = Image.open('img/3.jpg')
# plt.figure('meizi')
# plt.imshow(img)
# plt.axis('off')
# plt.show()
'''二.图像通道几何变换裁剪'''
# img = Image.open('img/3.jpg')
# img的属性信息
# print(img.size)
# print(img.mode)
# pr... | Python | 1 |
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_any(FingerprintVisitor)
}
}
struct FingerprintDeserialize;
impl<'de> CustomDeserialize<'de, Vec<String>> for FingerprintDeserialize {
fn deserialize<D>(deserialize... | Rust | 0 |
at equator has to be equal to the one defined in the
# ellipsoidmodel.
assert ellipsoid[0] == r
def test_ellipsoid_r_geocentric(self):
"""Test return of geocentric radius for all ellipsois."""
ellipsoid = geodesy.ellipsoidmodels().get('WGS84')
r = geodesy.ellipsoid_r_geoce... | Python | 1 |
chunk.parquet_metadata().decode().unwrap();
let iox_md_actual = md_actual.read_iox_metadata().unwrap();
let iox_md_expected = md_expected.read_iox_metadata().unwrap();
assert_eq!(iox_md_actual, iox_md_expected);
let schema_actual = md_actual.read_schema().unwrap();
let schema_e... | Rust | 0 |
rn out
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
if m.bias is not None:
m.bias.data... | Python | 1 |
, 3] + 1))
def _do_python_eval(self, output_dir='output', iou = 0.5):
rootpath = os.path.join(self.root, 'VOC' + self._year)
name = self.image_set[0][1]
annopath = os.path.join(
rootpath,
'Annotations',
... | Python | 1 |
LedsReport> {
let data = &mut [0];
match self.inner.read_report(data) {
Err(e) => Err(e),
Ok(_) => match KeyboardLedsReport::unpack(data) {
Ok(r) => Ok(r),
Err(_) => Err(UsbError::ParseError),
},
}
}
pub fn default_conf... | Rust | 0 |
apability_fits(cpu_cap, &a);
let s2 = pipeline_capability_fits(cpu_cap, &b);
s1.combine(s2)
},
}
}
}
fn pipeline_capability_fits(cpu: &Capability, instr: &Capability) -> Slot {
// think carefully.
// CPU SEMANTICS: 1 == no read/write, 0 == read/write in progress
// INSTR SEMANTICS: 1 == read/write ne... | Rust | 0 |
a[0], a[1], a[2], a[3]);
Vec4 { x, y, z, w }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn addition() {
let a = Vec2::new(1, 2);
let b = Vec2::new(4, -3);
assert_eq!(a, a + Vec2::ZERO);
assert_eq!(b, b + Vec2::ZERO);
assert_eq!(Vec2::new(5, -1)... | Rust | 0 |
f.Height)
self.event.set()
else:
self.q3.put(3)
self.event.set()
self.show_vectors_button.configure(self.Width * 0.15, self.Height * 0.85, 'raise')
self.hide_vectors_button.configure(self.Width * 0.15, self.Height * 0.85, 'lower')
... | Python | 1 |
from datetime import datetime
from lumibot.strategies.strategy import Strategy
"""
Strategy Description
An example of how to use limit orders and trailing stops to buy a stock and then sell it when it drops by a certain
percentage. This is a very simple strategy that is meant to demonstrate how to use limit orders a... | Python | 1 |
ind the
// closest value to the input color.
for (ix, col) in self.colormap.iter().enumerate() {
let hex = col.get_rgba();
let col_r = f32::from(hex[0]);
let col_g = f32::from(hex[1]);
let col_b = f32::from(hex[2]);
let col_a = f32::from(hex[3]... | Rust | 0 |
elf.embeddings.database = None
# Create an index for the list of text
self.embeddings.upsert(data)
# Set batch size to 1
self.embeddings.config["batch"] = 1
# Update data
data[0] = (0, "Feel good story: baby panda born", ... | Python | 1 |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import aibase_pb2 as aibase__pb2
class AIBaseServiceStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, ch... | Python | 1 |
# Copyright (C) 2019-2021 Estonian Information System Authority.
# See the file 'LICENSE' for copying permission.
from django.utils.crypto import get_random_string
from pathlib import Path
from cuckoo.common.storage import Paths
# Language code for this installation. All choices can be found here:
# http://www.i18ng... | Python | 1 |