text string | label_name string | labels int64 |
|---|---|---|
::{Config, Packet, Socket, SocketEvent};
#[test]
fn binding_to_any() {
// bind to 10 different addresses
let sock_without_config = (0..5).map(|_| Socket::bind_any());
let sock_with_config = (0..5).map(|_| Socket::bind_any_with_config(Config::default()));
let valid_socks: Vec<_> = sock_without_... | Rust | 0 |
win.y.lerp(map_range(i, 0, n, 0.0, 1.0)),
)
.w_h(w_over_3, win.h() / n as f32)
.color(color);
}
}
fn draw_center_bg(draw: &Draw, win: &Rect) {
let n = 200;
for i in 0..=n {
// hsl isn't mapping right for some reason...
// let color = rgb(
// 23. / 255.,
// 38. / 255... | Rust | 0 |
let has = self.check_pointer_lock();
if wants != has {
let canvas = self.gui_helpers.canvas_helper().canvas();
if wants {
canvas.request_pointer_lock();
} else if let Some(document) = canvas.owner_document() {
document.exit_pointer_loc... | Rust | 0 |
class Solution:
def search(self, nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
# Check if we found the target
if nums[mid] == target:
return mid
# Determi... | Python | 1 |
import pytest
import sqlalchemy as sa
import sqlalchemy.sql as sa_sql
from pcapi.core.reference import exceptions
from pcapi.core.reference import factories
from pcapi.core.reference import models
from pcapi.models import db
class ReferenceSchemeTest:
@pytest.mark.usefixtures("db_session")
def test_format_re... | Python | 1 |
import csv
import random
import numpy as np
import pandas as pd
from skmultiflow.data import HyperplaneGenerator
import matplotlib.pyplot as plt
for j in range(10):
# 创建超平面数据生成器
generator = HyperplaneGenerator(random_state=j, n_features=2, n_drift_features=2, mag_change=0,
... | Python | 1 |
if buffer.is_empty() {
break;
}
// do something here with buffer
// client.put(url).headers(headers).body(Body::from(&buffer))
f.write_all(&buffer).expect("Unable to write data");
buffer.len()
};
reader.consume(cons... | Rust | 0 |
{
// fn drop (&mut self) {
//println!("Dropping Material");
//debug("Dropping Material");
// }
//}
/*
static void material_generate_programs(material* m) {
for(int i = 0; i < m->num_entries; i++) {
material_entry* me = m->entries[i];
me->program = shader_program_new();
bool attached = false... | Rust | 0 |
import webrtcvad, pyaudio, speech_recognition as sr
class VAD:
def __init__(self, aggressiveness=3):
self.rate = 16000
self.frame_ms = 30
self.frame_samples = int(self.rate * self.frame_ms / 1000)
self.frame_bytes = self.frame_samples * 2
self.vad = webrtcvad.Vad(aggressi... | Python | 1 |
# 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 agreed to in writing, software
# distributed under the... | Python | 1 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import numpy as np
import torch
import torch.nn.functional as F
from fairseq import utils
from fairseq.criterions import Fairseq... | Python | 1 |
-True;"#,
err_value: Error::Evaluation{
source: EvaluationError::IllegalUnaryOperation{
opname: "-".to_string(),
value:"Boolean(true)".to_string()
}
},
}
evaluator_error_test_case! {
name: call_int_err,
input: r#"let... | Rust | 0 |
tart_tls=params.get("START_TLS", False))
if not l.bind():
raise Exception("Wrong credentials")
# search for users...
l.search(search_base=params["LDAPBASE"],
search_scope=ldap3.SUBTREE,
search_filter="(&" + params["SEARCHFILTE... | Python | 1 |
GePrecomp {
y_plus_x: Fe([ 0x1fd11ed0c84a7, 0x21b3ed2757e1, 0x73e1de58fc1c6, 0x5d110c84616ab, 0x3a5a7df28af64 ]),
y_minus_x: Fe([ 0x36b15b807cba6, 0x3f78a9e1afed7, 0xa59c2c608f1f, 0x52bdd8ecb81b7, 0xb24f48847ed4 ]),
xy2d: Fe([ 0x2d4be511beac7, 0x6bda4d99e5b9b, 0x17e6996914e01, 0x7b1... | Rust | 0 |
import requests
from youtube_transcript_api import YouTubeTranscriptApi
def test_network():
"""Test basic network connectivity."""
print("🌐 Testing network connectivity...")
try:
response = requests.get("https://www.google.com", timeout=5)
print(f"✅ Network OK: Status {response.status_code... | Python | 1 |
, n, decoded_t, n.logp + log_p, n.leng + 1)
score = -node.eval()
nextnodes.append((score, node))
# put them into queue
for i in range(len(nextnodes)):
score, nn = nextnodes[i]
nodes.put((score, nn))
# increase qsize... | Python | 1 |
}
#[inline]
pub(super) fn reschedule(&mut self, secs: u64) -> bool {
match self.state {
TimerState::Scheduled(timer_id) => {
reschedule(Duration::from_secs(secs), timer_id);
true
}
TimerState::Unscheduled(dur) => {
... | Rust | 0 |
;
}
extern "C" {
#[doc = " Updates all unicast hash bitmaps for receiving packet with any Unicast"]
#[doc = " Ethernet MAC addresses,the packet is routed to all VFs for which the RX"]
#[doc = " mode is accept packets that match the unicast hash table."]
#[doc = ""]
#[doc = " @param port_id"]
#[d... | Rust | 0 |
CHANNEL23"]
#[inline(always)]
pub fn ch23(&mut self) -> CH23_W {
CH23_W { w: self }
}
#[doc = "Bit 24 - Write 1, triggers DMA_CHANNEL24"]
#[inline(always)]
pub fn ch24(&mut self) -> CH24_W {
CH24_W { w: self }
}
#[doc = "Bit 25 - Write 1, triggers DMA_CHANNEL25"]
#[in... | Rust | 0 |
import numpy as np
import PIL.Image as Image
import spaces
import torch
from app import (
build_demo,
compute_gmm_likelihood,
load_model_from_hub,
plot_against_reference,
plot_heatmap,
)
@spaces.GPU
@torch.no_grad
def run_inference(model, img):
model = model.to('cuda')
img = img.to('cuda'... | Python | 1 |
ronome volume",
);
}
},
last_event,
);
if self.button_state != ButtonState::Default {
let mut paint = Paint::default();
paint.set_anti_alias(true);
match self.button_state {
ButtonState::Hov... | Rust | 0 |
annel, cli)
}
fn on_command(&self, command: &str, args: &[&str], user: &str, channel: &str, cli: &RtmClient) -> Result<(), Box<Error>> {
let sender = cli.sender();
if command == "hello" || command == "hi" {
sender.send_message(channel, "Hello there.")?;
}
else if co... | Rust | 0 |
from opencompass.models import HuggingFaceCausalLM
datasets = [
[
dict(
abbr='hellaswag_0',
eval_cfg=dict(
evaluator=dict(
type='opencompass.openicl.icl_evaluator.AccEvaluator'),
pred_postprocessor=dict(
options... | Python | 1 |
sg: str = ""):
if type(obj) is not expected_type:
w(
msg
+ f":Object '{obj}' is of type '{type(obj)}' where '{expected_type}' was expected!"
)
def require_type(obj, required_type, msg: str = ""):
if type(obj) is not required_type:
e(
Code.INVALID_TYP... | Python | 1 |
.stdout(regex_match(r"(?i)hidden course").not())
.stderr(predicate::str::is_empty());
}
// More to test the test server than the actual program
#[distributed_slice(TESTS)]
fn can_see_the_hidden_course_when_logged_in() {
log_in();
command()
.args(&["courses"])
.assert()
.success(... | Rust | 0 |
2;
a0.add_assign(&z3);
let mut a1 = z3;
a1.mul_by_nonresidue(self.extension_field.field());
a1.add_assign(&z2);
let mut a2 = tmp;
a2.mul_by_nonresidue(self.extension_field.field());
let mut t2 = a0;
t2.mul_assign(&a1);
t2.sub_assign(&tmp);
... | Rust | 0 |
omicAdd: VkBool32,
shaderSharedFloat32Atomics: VkBool32,
shaderSharedFloat32AtomicAdd: VkBool32,
shaderSharedFloat64Atomics: VkBool32,
shaderSharedFloat64AtomicAdd: VkBool32,
shaderImageFloat32Atomics: VkBool32,
shaderImageFloat32AtomicAdd: VkBool32,
sparseImageFloat32Atomics: VkBool32,
... | Rust | 0 |
import speedtest
import json
from ping3 import ping
try:
s = speedtest.Speedtest()
s.get_best_server() # ⚠️ This line is failing
download = s.download()
upload = s.upload()
ping_raw = s.results.ping
count = 4
lost = 0
total_ping = 0
successful_pings = 0
for _ in range(count):
... | Python | 1 |
from pep600_compliance.images import base, package_manager
class RockyLinux(base.Base):
def __init__(self, image, eol, packages, machines):
_, version = image.split(":")
self._packages = packages
super().__init__(
image, "rockylinux", version, eol, package_manager.DNF(), machin... | Python | 1 |
# -*- coding: utf-8 -*-
"""
@File : Sound.py
@Time : 2022/10/22 16:08
@Author : DoooReyn<jl88744653@gmail.com>
@Desc : 音效配置
"""
from enum import unique, Enum
@unique
class WindowsSounds(Enum):
"""Windows系统音频"""
Background = "Windows Background"
Foreground = "Windows Foreground"
Logon = "Win... | Python | 1 |
from __future__ import annotations
from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel, QTextBrowser
class PreviewPanel(QWidget):
"""Preview label + QTextBrowser wrapper."""
def __init__(self, translate):
super().__init__()
self.translate = translate
layout = QVBoxLayout(self)... | Python | 1 |
TempPath {
fn drop(&mut self) {
// Note that this is a synchronous call. We can't really return a future
// to do this.
let _ = std::fs::remove_file(&self.0);
}
}
/// A temporary async file.
pub struct NamedTempFile {
path: TempPath,
file: fs::File,
}
impl NamedTempFile {
... | Rust | 0 |
kills": {{
"AI & ML": ["Skill 1", "Skill 2"],
"Programming": ["Python", "JavaScript"],
"APIs & DBs": ["Stripe API", "PostgreSQL"]
}},
"education": [
{{
"deg... | Python | 1 |
"""Minimal configuration for Litestar MCP Plugin."""
from dataclasses import dataclass
from typing import Any, Optional
@dataclass
class MCPConfig:
"""Minimal configuration for the Litestar MCP Plugin.
The plugin uses Litestar's opt attribute to discover routes marked for MCP exposure.
Server name and v... | Python | 1 |
from multiprocessing import Process
import os
import numpy as np
import librosa
from librosa.core import load
from librosa.filters import mel as librosa_mel_fn
mel_basis = librosa_mel_fn(sr=24000, n_fft=1024, n_mels=100, fmin=0, fmax=12000)
from tqdm import tqdm
import pandas as pd
import pyworld as pw
def get_worl... | Python | 1 |
)
if len(html_primary) == 0: # 再获取一遍
resp = requests.get(url, headers=self.headers, timeout=15)
html = etree.HTML(resp.text)
# html_primary获取影视名字的短链接列表:['/voddetail/12299.html',...]
html_primary = html.xpath('/html/body/div[1]/div/div[1]/div/... | Python | 1 |
while start.elapsed().as_millis() <= timeout as u128 {
if let Ok(data) = socket.read() {
return Ok(data.to_vec())
}
}
// Timeout
if timeout_ms == 0 {
Err(ChannelError::BufferEmpty)
} else {
... | Rust | 0 |
"PACD",
"CPER",
"NTK",
"SOCL",
"CLVS",
"ANGI",
"ARWRD",
"DLPH",
"IPFF",
"DDMG",
"KFH",
"MFRM",
"MN",
"MOVED",
"VAC",
"BUI",
"AVV",
"KEYpE.CL",
"LMCA",
"LMCB",
"DTEpA.CL",
"DTEpC.CL",
"OFF",
"ONN",
"AGLS",
"ASBCW",
"BBCN",
"FLRN",
"SGYPD",
"SGYPU",
"SST",
... | Rust | 0 |
#! /usr/bin/env python
"""Script to setup NETCONF RBAC using NACM to allow PRIV01 users read access
This script will retrieve information from a device.
Copyright (c) 2018 Cisco and/or its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documen... | Python | 1 |
rting demultiplexing in {} end mode...",
if paired_end { "paired" } else { "single" });
let mut total_reads: u64 = 0;
let mut identified_reads: u64 = 0;
let mut extra_barcodes: HashMap<String, u64> = HashMap::new();
let mut header = String::new();
let mut line = String::new();
let mut barcode = String::new();
... | Rust | 0 |
0x52, 0x99, 0x6e, 0x57, 84}
DEFINE_DEVPROPKEY!{DEVPKEY_DeviceContainer_IsNetworkDevice,
0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 85}
DEFINE_DEVPROPKEY!{DEVPKEY_DeviceContainer_IsDefaultDevice,
0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 86}
DEFI... | Rust | 0 |
o: Resposta muito extensa")
# ============================================================================
# Técnica 3: Prompt Chaining
# ============================================================================
def prompt_chaining_strategy():
"""Prompt Chaining: Quebrar análise em etapas específicas"""
... | Python | 1 |
ěng"),
('验', "yàn"),
('骍', "xīng"),
('骎', "qīn"),
('骏', "jùn"),
('骐', "qí"),
('骑', "qí"),
('骒', "kè"),
('骓', "zhuī"),
('骔', "zōng"),
('骕', "sù"),
('骖', "cān"),
('骗', "piàn"),
('骘', "zhì"),
('骙', "kuí"),
('骚', "sāo"),
('骛', "wù"),
('骜', "ào"),
('骝',... | Rust | 0 |
d in word_list:
if attr_map[word.encode('utf-8')] == []:
continue
ans.append(attr_map[word.encode('utf-8')][0].decode('utf-8'))
return ans
match = []
for w in attr_ac.iter(pred_name.encode('utf-8')):
match.append(w[1][1].decode('utf-8'))
if not len(ma... | Python | 1 |
import argparse
import json
import browsergym.webarena # noqa F401 register webarena tasks as gym environments
import gymnasium as gym
parser = argparse.ArgumentParser(description='Calculate average reward.')
parser.add_argument('output_path', type=str, help='path to output.jsonl')
args = parser.parse_args()
if __... | Python | 1 |
is unavailable
wiim_speaker._available = False
wiim_speaker.coordinator.last_update_success = True
assert media_player.available is False
# Case 3: Last update was not successful
wiim_speaker._available = True
wiim_speaker.coordinator.last_update_success = False
... | Python | 1 |
// For example sign the input parameters or generate a random token.
fn tag(&mut self, usage: u64, grant: &Grant) -> Result<String, ()>;
}
/// Generates tokens from random bytes.
///
/// Each byte is chosen randomly from the basic `rand::thread_rng`. This generator will always
/// succeed.
pub struct RandomGenerat... | Rust | 0 |
g.BBRUUID,
g.geometry,
g.bygningstype,
g.building_area_m2,
'uuid_matched' as join_status,
{chunk_idx + 1} as chunk_id
FROM (
SELECT '{chunk_ids_str}' as id_list
) chunk_ids
INNER ... | Python | 1 |
to DB & get handles to user DB and the books collection
let client = Client::with_uri_str("mongodb://db:27017/")
.expect("Unable to connect to MongoDB");
let db = client.database("running-mate");
let collection = db.collection("users");
// Spawn the reminder task
actix_rt::spawn(running_mat... | Rust | 0 |
agent: &Agent,
player: &Player,
cmd: &AddAndBlessReplicaVersionCmd,
context_time: Time,
) -> Result<Vec<SignedIngress>, String> {
let replica_version_id = cmd.replica_version_id.clone();
let replica_version_record =
serde_json::from_str::<ReplicaVersionRecord>(&cmd.replica_version_value)... | Rust | 0 |
tors (dJ/dV):\n {}\nGradient wrt Outside Vectors (dJ/dU):\n {}\n".format(
*skipgram("c", 3, ["a", "b", "e", "d", "b", "c"],
dummy_tokens, dummy_vectors[:5,:], dummy_vectors[5:,:], dataset)
)
)
print ("Expected Result: Value should approximate these:")
print("""Loss: 11.... | Python | 1 |
.with_context(file_ctx)?;
let start_headers = Instant::now();
let mut seq = cli.start_sequence().await?;
seq.send_messages(&[
ClientMessage::Restore(Restore {
headers: HashMap::new(),
jobs: 1,
data: header,
})
]).await?;
loop... | Rust | 0 |
Err(error::Error::No(EOPNOTSUPP))
}
fn rversion(&mut self, ms: u32, ver: &str) -> Result<Fcall> {
match ver {
P92000L => Ok(Fcall::Rversion {
msize: ms,
version: ver.to_owned(),
}),
_ => Err(error::Error::No(EPROTONOSUPPORT)),
... | Rust | 0 |
ub const NT_PRPSINFO: Elf_Word = 3;
pub const NT_PRXREG: Elf_Word = 4;
pub const NT_TASKSTRUCT: Elf_Word = 4;
pub const NT_PLATFORM: Elf_Word = 5;
pub const NT_AUXV: Elf_Word = 6;
pub const NT_GWINDOWS: Elf_Word = 7;
pub const NT_ASRS: Elf_Word = 8;
pub const NT_PSTATUS: Elf_Word = 10;
pub const NT_PSINFO: Elf_Word = 1... | Rust | 0 |
}
resno = resno.wrapping_add(1)
}
opj_aligned_free(h.mem as *mut libc::c_void);
let mut ret_0 = opj_sparse_array_int32_read(
sa,
(*tr_max).win_x0.wrapping_sub((*tr_max).x0 as OPJ_UINT32),
(*tr_max).win_y0.wrapping_sub((*tr_max).y0 as OPJ_UINT32),
(*tr_max).win_x1.wrapping_sub((*tr_max).x0 as O... | Rust | 0 |
rhs.samplers,
sets: self.sets + rhs.sets,
}
}
}
impl Mul<u32> for DescriptorPoolSetup {
type Output = Self;
fn mul(self, rhs: u32) -> Self::Output {
Self {
storage_buffers: self.storage_buffers * rhs,
combined_image_samplers: self.combined_image_sampler... | Rust | 0 |
String>,
formatter: taplo::formatter::OptionsIncompleteCamel,
}
pub type World = Arc<RwLock<WorldState>>;
pub fn create_server() -> Server<World> {
Server::new()
.on_request::<request::Initialize, _>(handlers::initialize)
.on_request::<request::FoldingRangeRequest, _>(handlers::folding_ranges)... | Rust | 0 |
TWELVE_FIFTHS
} else {
let g1 = self.g_func(1.0);
let g2 = self.g_func(2.0);
let g3 = self.g_func(3.0);
let g4 = self.g_func(4.0);
let numerator =
g4 - 4.0 * g3 * g1 - 3.0 * g2 * g2 + 12.0 * g2 * g1 * g1 - 6.0 * g1.powi(4);
... | Rust | 0 |
tor."""
async def read(self) -> Union[EOFType, ResponseType]:
# Behind the scenes everything goes through the
# async iterator. So this path should not be reached.
raise NotImplementedError()
class StreamStreamCallResponseIterator(
_StreamCallResponseIterator, _base_call.StreamStreamC... | Python | 1 |
bitmap: JObject,
flipY: jboolean,
) {
let mut data = super::super::utils::image::get_bytes_from_bitmap(env, bitmap);
if !data.0.is_empty() {
if flipY == JNI_TRUE {
crate::common::utils::gl::flip_in_place(
data.0.as_mut_ptr(),
data.0.len(),
... | Rust | 0 |
# GridCal
# Copyright (C) 2022 Santiago Peñate Vera
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3 of the License, or (at your option) any later version.
#
# This pr... | Python | 1 |
= e.1 {true} else {false}).count(),
test_result: report.test_result.sum.clone(),
unit_err: report.result.iter().filter(|e| if let RefactorResult::UnitErr(..) = e.1 {true} else {false}).count(),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_to_report() {
... | Rust | 0 |
_check_follow_enable_sites(config_key='rss_follow_enable_sites')
def __check_signin_follow_enable_sites(self, installed_plugin_ids: List[str] = None) -> bool:
"""
判断签到站点的跟随按钮是否打开
"""
return self.__check_follow_enable_sites(config_key='signin_follow_enable_sites', plugin_id=self.__pl... | Python | 1 |
*failed += 1;
if !summary_only {
println!("test {} ... {}FAILED{}", test_no + 1, ASCII_RED, ASCII_RESET);
println!(" {}expected{}: {}", ASCII_GREEN, ASCII_RESET, expected);
println!(" {}actual{}: {}", ASCII_RED, ASCII_RESET, actual);
println!(
" {}difference{}: {}",
... | Rust | 0 |
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
]);
/// I384 big-endian `u32` represented 2.
pub const BE_U32_2: I384<BigEndian, U32Repr> = I384::<BigEndian, U32Repr>::from_array([
0x0000_0000,
0x0000_0000,
0x0000_0000,
... | Rust | 0 |
#!/usr/bin/python
import sys, os, imp, logging, time, subprocess
from twisted.internet import reactor
logger = logging.getLogger('yaypm.srcmon')
def monitor():
def modules2watch():
modules2watch = {}
pythonDir = sys.modules["os"].__file__.rsplit("/", 1)[0]
for m in sys.modules.values():
... | Python | 1 |
om;
use super::*;
use num_traits_plus::assert_approx_eq;
use crate::{
attributes::Chroma,
hue::{Hue, Sextant::*},
rgb::RGB,
ColourBasics, RGBConstants,
};
const NON_ZERO_CHROMA_PROPS: [f64; 7] = [0.01, 0.025, 0.5, 0.75, 0.9, 0.99, 1.0];
const SHADE_TINT_CHROMA_PROPS: [f64; 8] = [0.001, 0.01, 0.025, ... | Rust | 0 |
status_counts[status] = status_counts.get(status, 0) + 1
parsed_trackings.append(
{
"name": name,
"tracking_number": track["tracking_number"],
"slug": track["slug"],
"link": f"{BASE}{track['slug']}/{track['t... | Python | 1 |
width=0.5, alpha=0.2)
# Add text annotations
for (i, j), z in np.ndenumerate(arr):
if abs(z) < 1e-6:
continue
if is_count_data:
text = f'{int(z)}'
threshold = np.max(arr) * 0.5
else:
... | Python | 1 |
import frappe
@frappe.whitelist()
def list(
filters=None,
or_filters=None,
fields=["name"],
order_by=None,
limit_page_length=0,
limit_start=0,
):
try:
project_list = frappe.get_list(
"Project",
filters=filters,
or_filters=or_filters,
... | Python | 1 |
(2)@ iznosi @hspacept(2)@ @result@? @hspacept(10)@ @lib.check_number(number,50)@
@/repeat@use ckb_channel::{bounded, Receiver, Select, Sender};
use ckb_network::{
bytes::Bytes, Behaviour, CKBProtocolContext, CKBProtocolHandler, Peer, PeerIndex, ProtocolId,
TargetSession,
};
use ckb_util::RwLock;
use futures::... | Rust | 0 |
o()),
I32X4_REPLACE_LANE => I32x4ReplaceLane(Uint8::deserialize(reader)?.into()),
I64X2_REPLACE_LANE => I64x2ReplaceLane(Uint8::deserialize(reader)?.into()),
F32X4_REPLACE_LANE => F32x4ReplaceLane(Uint8::deserialize(reader)?.into()),
F64X2_REPLACE_LANE => F64x2ReplaceLane(Uint8::deserialize(reader)?.into()),
... | Rust | 0 |
])
# Process each AP's heatmap
ap_heatmaps = []
for ap_name in ap_names:
if ap_name in wifi_data:
heatmap_str = wifi_data[ap_name]
heatmap_complex = np.array(
[complex(val) for val in heatmap_str], dtype... | Python | 1 |
# 250924 Day 15 of Python
# Day 15 Project
# Making the Coffee Machine project
# print report.
# check resources sufficient?
# process coins.
# check transaction successful?
# Make Coffee.
# 내가 짠 코드! 근데 넘 길당 ㅎ
# 어쨌든 해결!!
# MENU = {
# "espresso": {
# "ingredients": {
# "water": 50,
# ... | Python | 1 |
from click import ClickException
import pytest
from purl.url_parser import ParsedURL, UrlParser
from purl.enums import Protocol
@pytest.mark.parametrize(
"test_input,expected,raises",
[
("http://github.com", ParsedURL(Protocol.HTTP, "github.com", 80), False),
("https://github.com", ParsedURL(... | Python | 1 |
1) + num;
//println!("n:{}", n);
res.push(n % 5 == 0);
pre = n;
}
return res;
}
///
/// 我们先来一个结论f(i)%5=(f(i-1)%5*2+k)%5,因此我们每次只需要保留上一位的取模结果即可
/// 我们把f(i)%5看成一个function m(i),则有m(i)=(m(i-1)*2+k)%5
///
/// 模运算法则
///
/// (a + b) % p = (a % p + b % p) % p
///
///
///
///
pub fn prefixes_div_... | Rust | 0 |
def slovavmeste():
N = int(input("Количество слов: "))
slovokstroka = ""
for i in range(N):
slovo = input("Введите слово: ")
slovokstroka += slovo + " "
print("Ваши слова:", slovokstroka)
slovavmeste()
| Python | 1 |
ent[key] = value
else: # don't override duplicate keys, share a list instead
# generally duplicate keys are outputs (e.g. OnMapSpawn)
if isinstance(ent[key], list): # more than 2 of this key
ent[key].append(value)
... | Python | 1 |
schedule_upgrade_deadline)
duration_limit_upgrade_deadline = get_user_course_expiration_date(enrollment.user, enrollment.course)
assert duration_limit_upgrade_deadline is not None
message = generate_course_expired_message(enrollment.user, enrollment.course)
self.assertDateInMessage(du... | Python | 1 |
import numpy as np
def fitness(x):
counter = 0
n = len(x)
for i in range(n - 1):
for j in range(i + 1, n):
if x[i] - x[j] == i - j:
counter += 1
return n * (n - 1) / 2 - counter
def gen(dim, n):
pop = []
for i in range(dim):
x = np.random.permutati... | Python | 1 |
| BinaryOpKind::Less
| BinaryOpKind::Greater
| BinaryOpKind::GreaterEqual
)
}
pub fn as_string(&self) -> &str {
match self {
BinaryOpKind::Add => "+",
BinaryOpKind::Subtract => "-",
BinaryOpKind::Multiply => "*",
Bi... | Rust | 0 |
str],
typer.Option('--model', '-m', help='The name of the model to add'),
],
strategy: Annotated[
ModelPolicyStrategyMode,
typer.Option('--strategy', '-s', help='How to spread traffic across models'),
],
retry_attempts: Annotated[
int,
... | Python | 1 |
();
assert_eq!(3, calc_min_frame(&lights));
}
#[test]
fn render_test() {
let mut lights = get_readings();
advance_lights(&mut lights);
advance_lights(&mut lights);
advance_lights(&mut lights);
let expected = "#...#..###\n".to_string()
+ "#...#...#... | Rust | 0 |
"])
.run()
.stdout_is("1 1 2 2 1 notrailingnewline.txt\n");
}
/// Test for a file that has 100 empty lines (that is, the contents of
/// the file are the newline character repeated one hundred times).
#[test]
fn test_file_many_empty_lines() {
new_ucmd!()
.args(&["-clmwL", "manyemptylines.tx... | Rust | 0 |
nvidia GPUs
daemon_sets = [ds for ds in daemon_sets if "nvidia" not in ds["name"]]
# separate DaemonSets without requests, as only requests are what impacts
# scheduling of pods and reduces a node's remaining allocatable resources
req_daemon_sets = [
ds for ds in daemon_sets if ds["cpu_request"]... | Python | 1 |
=> Err(Error::UserDataTypeMismatch),
}
}
} else {
Err(Error::FromLuaConversionError {
from: "missing argument",
to: "userdata",
message: None,
})
... | Rust | 0 |
to_string_lossy()) title=(slide.name());
figcaption { (slide.name()) }
}
}
}
}
}
},
);
println!("{}", html.into_string());
}
use criterion::{criterion_group, criterion_main... | Rust | 0 |
ve(), dst)?;
}
Index::Inserted(_) => {
let header = self.table.resolve(&index);
assert!(!header.is_sensitive());
if !dst.has_remaining_mut() {
return Err(EncoderError::BufferOverflow);
}
dst.pu... | Rust | 0 |
,
help: None,
requires: None,
blacklist: None,
possible_vals: None,
index: 0,
num_vals: None,
min_vals: None,
max_vals: None,
val_names: None,
validator: None,
overrides: None,
... | Rust | 0 |
The name of this ModelsSubdivision. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this ModelsSubdivision.
:param name: The name of this ModelsSubdivision. # noqa: E501
:type: str
"""
sel... | Python | 1 |
ces["schemes"]:
_protocol = "http"
else:
_protocol = self.api_resources["schemes"][0]
_base_url = "{}://{}{}".format(
_protocol, self.api_resources["host"], self.api_resources["basePath"]
)
return _base_url
def _compile_bas... | Python | 1 |
import time
from geti_sdk.data_models import Job, Task
from geti_sdk.data_models.algorithms import Algorithm
from geti_sdk.http_session import GetiRequestException
from geti_sdk.rest_clients import TrainingClient
from .enums import SdkTestMode
def attempt_to_train_task(
training_client: TrainingClient,
task... | Python | 1 |
from flask import Flask, request
import hello
import user_testing
import interface
import analyst_interface
import logging
from logging.handlers import RotatingFileHandler
import os
from services.nl_to_sql_service import bp as nl_to_sql_bp
from services.suggestions_service import bp as suggestions_bp
from services.anal... | Python | 1 |
(cons_width as i32, h)
} else {
println!("Scaling down! The text will look worse!");
let w = (rect_width as f32 / hr) as i32;
(w, cons_height as i32)
}
} else {
(rect_width as i32, rect_height as i32)
};
let cx = (SCREEN_WIDTH as i32 ... | Rust | 0 |
move {
match rx.read().await {
Ok(item) => Some((Ok(item), rx)),
Err(e) => Some((Err(e), rx)),
}
})
}
#[derive(Debug, Clone)]
pub enum CompressionSwitcherProvider {
On(Arc<DeflateExtProvider>),
Off,
}
impl PartialEq for CompressionSwitcherProvider {
fn eq(&self... | Rust | 0 |
teMutexW(GLOBAL_SMBUS_MUTEX_NAME, throwable = False)
if mtx.handle:
print(f'Mutex "{LOCAL_SMBUS_MUTEX_NAME}" created!')
else:
print(f'Mutex "{LOCAL_SMBUS_MUTEX_NAME}" cannot opened and cteated!')
rc = -1
mtx = OpenMutexW(GLOBAL_SMBUS_MUTEX_... | Python | 1 |
e__)
+ '" module.\n'
)
msg += "=" * len(msg) + "\n" + "\n".join(problems)
raise Py5ImportError(msg)
# add the necessary helper methods for for dynamic variables
code_src = PY5_HEADER + "\n\n\n" + code_src
# parse and compile the altered code
... | Python | 1 |
()?;
///
/// assert_eq!(false, metadata.permissions().readonly());
/// Ok(())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn readonly(&self) -> bool {
self.0.readonly()
}
/// Modifies the readonly flag for this set of permissions. If the
/// `... | Rust | 0 |
\xcb\xc2P\x5cC\x83q<\xae4W;\
tM/\xcfW\xf4\xa3'\x0e\xe2\x09]\xa3lGA\
\x1b\x9fL@$\xeci\x98d\x821\xe0\x0cS!\xd7\
\x92\x068\xf8f\x083\xd6\xdc_C`\xa3\x8e\xcd]\
G9\x9a\x95\xbc\x9c\x9a\x9a\xa4f;\x874'\xa8\xb9\
\xeb\x93f\xfa\xadW\xe5o\xb5\x03\xaeM\x9b\xea\xb5_\
\x95\xbe\xd4\x0e\xb96o\xaa\xd5~V\xfbP:\xe4\xd9\
\xbe\xabU\xf9[\xed... | Python | 1 |
logger.info("successfully explored top-level names: {}".format(", ".join(shards.keys())))
# Write output
out = {
"pip-package": args.package,
"pip-version": args.version,
"shards": shards,
"rootIDs": root_ids,
}
with realopen(args.out, "w+") as f:
try:
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.