text string | label_name string | labels int64 |
|---|---|---|
,
File(RefMut<'a, io::BufWriter<fs::File>>),
}
impl<'a> Write for OutputWriter<'a> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match *self {
OutputWriter::StdOut => io::stdout().lock().write(buf),
OutputWriter::StdErr => io::stderr().lock().write(buf),
O... | Rust | 0 |
#Faça um algoritimo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
preço = float(input('Qual o preço do produto? R$'))
novo = preço - (preço * 5 / 100)
print('O preço que custava R${}, na promoção com desconto de 5% vai custar R${}'.format(preço, novo))
| Python | 1 |
achine", row.virtual_machine)
volume = find(machine.volumes, lambda v: v.volume_id == row.volume_id)
if not volume:
# This volume is not managed by Press. Ignore
continue
# Always downgrade performance
iops = min(row.recommended_iops, volume.iops)
throughput = min(row.recommended_throughput, volume.th... | Python | 1 |
from llama_index.callbacks.aim.base import AimCallback
__all__ = ["AimCallback"]
| Python | 1 |
import torch
# adapted from
# https://github.com/facebookresearch/llama/blob/main/llama/model.py
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
t = torch.arange(end, device=freqs.device, dtype=torch.float32)... | Python | 1 |
| taw-lal'", "properly, to strew over, i.e. (by implication) to cover in or plate (with beams)"],
"H2927":["טְלַל", "ṭᵉlal | tel-al'", "to cover with shade"],
"H2928":["טֶלֶם", "Ṭelem | teh'-lem", "Telem, the name of a place in Idumaea, also of a temple doorkeeper"],
"H2929":["טַלְמֹון", "Ṭalmôwn | tal-mone'", "Talmon,... | Python | 1 |
} else {
parapet.run().unwrap();
}
}
<filename>rustorio-core/src/prototypes/prototypes/storage_tank.rs
use serde::{Deserialize, Serialize};
use crate::prototypes::{Prototype, Visitor};
use crate::types::*; // TODO: Import only specific types
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct... | Rust | 0 |
import wx
from .backend_agg import FigureCanvasAgg
from .backend_wx import _BackendWx, _FigureCanvasWxBase
from .backend_wx import ( # noqa: F401 # pylint: disable=W0611
NavigationToolbar2Wx as NavigationToolbar2WxAgg)
class FigureCanvasWxAgg(FigureCanvasAgg, _FigureCanvasWxBase):
def draw(self, drawDC=None... | Python | 1 |
import sys
from agno.agent import Agent
try:
from agno.tools.docker import DockerTools
docker_tools = DockerTools(
enable_container_management=True,
enable_image_management=True,
enable_volume_management=True,
enable_network_management=True,
)
# Create an agent with D... | Python | 1 |
dices_20hz = np.round(np.linspace(0, len(data_chunk) - 1, 120)).astype(int)
data_chunk_subsampled = data_chunk[indices_20hz]
npy_name = npy_name_base + f"_{npy_idx}.npy"
# np.save(os.path.join(data_dir, npy_name), data_chunk_subsampled)
accl = data_chunk_subsampled[:,0:3]
... | Python | 1 |
::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> FunctionExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
FunctionExpression { _tab: table }
}
#[... | Rust | 0 |
# Copyright 2020 The MediaPipe Authors.
#
# 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 ... | Python | 1 |
FFFF_FFFF);
assert_eq!(cursor.read_fourcc().unwrap(), WAVE_SIG);
assert_eq!(cursor.read_fourcc().unwrap(), DS64_SIG);
let ds64_size = cursor.read_u32::<LittleEndian>().unwrap();
let form_size = cursor.read_u64::<LittleEndian>().unwrap();
let data_size = cursor.read_u64::<LittleEndian>().unwrap();
... | Rust | 0 |
e' : [
(r'[\r\n]+', Whitespace, '#pop'),
(r';.*?$', Comment, '#pop'),
include('whitespace')
],
'instruction-args': [
(r',', Punctuation),
(r'\[', Punctuation, 'deref'),
include('arg'),
include('instruction-line')
... | Python | 1 |
(&content).unwrap();
println!("Part two: {}", result);
}
//! A [`crate::sharded::Cache`] uses the same basic file-based second
//! chance strategy as a [`crate::plain::Cache`]. However, while the
//! simple plain cache is well suited to small caches (down to 2-3
//! files, and up maybe one hundred), this sharded v... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2019 Google Inc. 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 requir... | Python | 1 |
"""
API endpoints для управления клиникой
"""
from typing import List, Optional, Dict, Any
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from app.api.deps import get_db, require_admin
from app.models.user import User
from app.services.clinic_management_service ... | Python | 1 |
input = CellInput::new_cellbase_input(0);
// at least issue some shannons to make dao field valid.
let output = {
let empty_output = CellOutput::new_builder().build();
let occupied = empty_output
.occupied_capacity(Capacity::zero())
.expect("defau... | Rust | 0 |
is who controls the two threads described above. Presumably one
// of regular rust threads, tokio, or timely.
// - Should we hard-code the Key, Val, Time, Diff types everywhere or introduce
// them as type parameters? Materialize will only be using one combination of
// them (two with `()` vals?) but the gener... | Rust | 0 |
from setuptools import setup, find_packages
from typing import List
def get_requirements() -> List[str]:
try:
with open("requirements.txt", 'r') as file:
return [line.strip() for line in file.readlines() if line.strip() and line.strip() != '-e .']
except FileNotFoundError:
print("r... | Python | 1 |
tes/ahash
///
pub struct Cache<K, V, S = RandomState> {
base: BaseCache<K, V, S>,
value_initializer: Arc<ValueInitializer<K, V, S>>,
}
// TODO: https://github.com/moka-rs/moka/issues/54
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl<K, V, S> Send for Cache<K, V, S>
where
K: Send + Sync,
V: Se... | Rust | 0 |
::BigInt;
use num::bigint::ToBigInt;
use num::traits::One;
// https://www.codewars.com/kata/559b8e46fa060b2c6a0000bf/solutions/rust
<filename>common/src/error.rs<gh_stars>1-10
use std::any::{Any, TypeId};
use std::borrow::Cow;
use std::collections::HashMap;
use std::error::Error;
use std::fmt::{Debug, Display};
use st... | Rust | 0 |
pr(C)] #[derive(Clone, Copy, Debug)]
pub struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTIDCOUNT_INPUT {
pub Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT,
pub DeviceHandle: ::HANDLE,
pub CryptoSessionHandle: ::HANDLE,
}
#[repr(C)] #[derive(Clone, Copy, Debug)]
pub struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTIDCOUNT_O... | Rust | 0 |
#[test]
fn test_lt() {
let mut domain = Domain::new()
.lt(Value::Included(5))
.gt(Value::Secluded(3))
.gt(Value::Secluded(1));
assert_eq!(domain.repr(), "(3;6)".to_string())
}
#[test]
fn test_generate() {
fn rec(n: i32, c: &()) {
... | Rust | 0 |
black_box(criteria.x as u16),
black_box(bitmap.clone()),
)
})
},
);
}
}
fn read_bitmap(c: &mut Criterion) {
let mut group = c.benchmark_group("Read bitmap");
for (idx, criteria) in [
Extent::new(1, 1),
... | Rust | 0 |
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3"
def get_python_executable():
current_file_path = os.path.abspath(__file__)
project_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(current_file_path))))
return os.path.join(project_path, ".venvs/.venv-whisper/bin/python")... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Created on Mon May 20 08:58:55 2024
@author: sedla
"""
import doaLib as dsp
import time
num_signals = 1
freq = [20e3]
theta_deg = [20]
num_elem = 5
delta = 0.5
sample_rate = 1e6
num_samples = 100000
snr_dB = 20
ref_data = dsp.generate_data_ULA(freq, theta_deg, num_elem, delta, sample_... | Python | 1 |
Status"]
pub status: STATUS,
#[doc = "0x14 - External Multipurpose Crystal Oscillator Control"]
pub xoscctrl: [XOSCCTRL; 2],
#[doc = "0x1c - DFLL48M Control A"]
pub dfllctrla: DFLLCTRLA,
_reserved7: [u8; 3usize],
#[doc = "0x20 - DFLL48M Control B"]
pub dfllctrlb: DFLLCTRLB,
_reserve... | Rust | 0 |
# SPDX-FileCopyrightText: 2025 Greenbone AG
#
# SPDX-License-Identifier: GPL-3.0-or-later
import unittest
from unittest.mock import MagicMock, patch
from gvm.protocols.http.openvasd import OpenvasdHttpAPIv1
class TestOpenvasdHttpApiV1(unittest.TestCase):
@patch("gvm.protocols.http.openvasd._openvasd1.create_ope... | Python | 1 |
>;
impl R {
#[doc = "Bit 0 - State of the USB plug contact detector."]
#[inline(always)]
pub fn plug_contact(&self) -> PLUG_CONTACT_R {
PLUG_CONTACT_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - State of charger detection. This bit is a read only version of the state of the analog signa... | Rust | 0 |
kus"
result_state = agent.run(mock_state)
if (
hasattr(result_state, "new_enriched_article")
and result_state.new_enriched_article
):
result = result_state.new_enriched_article
print(f" Email enrichment successful!")
print(f" Enhanced title: {result.enriched_tit... | Python | 1 |
! top_level {
it "should be less specific" {
assert_eq!(1u, 1u);
}
describe! nested {
it "should be more specific" {
assert_eq!(2u, 2u);
}
}
}
<gh_stars>10-100
//! Statistical hypothesis tests
//!
//! Fore more information:
//! <a href="https://en.wikipedia.org/wiki/... | Rust | 0 |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import sys
def plot_matrix(arr, figname="arr"):
print("Creating figure: ", figname)
myarr = np.copy(arr)
for i in range(myarr.shape[0]):
for j in range(myarr.shape[1]):
myarr[i,j] = np.log10(abs(arr[i,j]))
plt... | Python | 1 |
stack")
stacknames = obj.get("stacknames", [])
stacknode = node.child("__stack")
framenode = None
for i in range(len(stack)):
name = stacknames[i] if stacknames else None
if name and name.startswith("frame:"):
framenode = stacknode.child(name[6:])
... | Python | 1 |
let map = Beatmap::from_path(map_path).await.map_err(PpError::from)?;
maps.insert(score.beatmap_id, map);
}
let map = maps.get(&score.beatmap_id).unwrap();
map.stars().mods(score.mods.bits()).calculate().star... | Rust | 0 |
import math
# Función para calcular el producto de combinaciones a partir de los valores de alpha
def comb_product(X, alphas):
result = 1
total = 0
for i, alpha in enumerate(alphas):
result *= math.comb(X - total, alpha)
total += alpha
return result
def print_suma_alphas(X, alphas):
... | Python | 1 |
author"
assert without_sql_comment(parser=parser_stub, line=line) == expected
def test_without_sql_comment_unspaced_comment():
line = "SELECT * FROM author --uff da"
expected = "SELECT * FROM author"
assert without_sql_comment(parser=parser_stub, line=line) == expected
def test_without_sql_comment_d... | Python | 1 |
protovend_version: Version::from_str("0.1.8").unwrap(),
vendor: vec![],
};
let actual_config = load_config(&config_path).unwrap();
assert_eq!(expected_config, actual_config);
}
#[test]
fn test_config_from_legacy_config() {
let legacy_config = LegacyProtovendCon... | Rust | 0 |
#Author-syuntoku14
#Description-Generate URDF file from Fusion 360
import adsk, adsk.core, adsk.fusion, traceback
import os
import sys
from .utils import utils
from .core import Link, Joint, Write
"""
# length unit is 'cm' and inertial unit is 'kg/cm^2'
# If there is no 'body' in the root component, maybe the corrdin... | Python | 1 |
from typing import List
import asyncpg
import genshin
from discord import utils
from utils import get_current_abyss_season
async def update_user_abyss_leaderboard(
abyss_data: genshin.models.SpiralAbyss,
user_data: genshin.models.PartialGenshinUserStats,
characters: List[genshin.models.Character],
u... | Python | 1 |
#upholstery.run('python manage.py runserver 0.0.0.0:8000')
return True
virtual_host = """
<VirtualHost *:8000>
ServerAdmin steve.zabak@childrens.harvard.edu
ServerName x-staging.indivo.org
DocumentRoot /web/indivo_server
Alias /static/ /web/indivo_server/static/
EnableMMAP On
EnableSendfile On
LogLevel... | Python | 1 |
XPAND, 5)
main_sizer.AddSpacer(15)
main_sizer.Add(button_sizer, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 4)
main_sizer.AddSpacer(5)
# 第二栏:选项
option_box = wx.StaticBox(self.panel)
option_box_sizer = wx.StaticBoxSizer(option_box, wx.HORIZONTAL)
self.auto_start = wx.Check... | Python | 1 |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Authors: Fred Senekal (FS)
# Contact: fred@silicogenesis.com
# License: GPLv3
"""
Implements class `VDWRadius` to provide van der Waals radii for atoms.
"""
class VDWRadius:
# Values below need to be checked
# VDW_RADIUS = {
# "H": 1.20,
# "H... | Python | 1 |
http://api.x.io/orders/12/items",
"type": "application/x-www-form-urlencoded",
"fields": [
{ "name": "orderNumber", "type": "hidden", "value": "12" },
{ "name": "productCode", "type": "text" },
{ "name": "quantity", "type": "number" }
]
},
... | Rust | 0 |
o excluir o arquivo da conversa {file_path}: {e}")
return False
def list_conversations(self):
conversations = list(self.messages_folder.glob('*'))
conversations.sort(key=lambda item: item.stat().st_mtime_ns, reverse=True)
return [c.stem for c in conversations]
def _save_api... | Python | 1 |
= Occurrences::NoneOrMore;
occurence.check(core::u16::MAX).unwrap();
}
#[test]
fn test_none_or_up_to_42_zero() {
let occurence: Occurrences = Occurrences::NoneOrMore;
occurence.check(0).unwrap();
}
#[test]
fn test_none_or_up_to_42() {
let occurence: Occurrences =... | Rust | 0 |
llate.to_dict(by_alias=by_alias)
return _dict
@classmethod
def from_dict(cls, obj: dict) -> DockerWorkerConfigV2Lightly:
"""Create an instance of DockerWorkerConfigV2Lightly from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return ... | Python | 1 |
'Aŋkúla', 'yi': 'אַנגאלע', 'yo': 'Ààngólà', 'yrl': 'Ãgura', 'yue': '安哥拉', 'yue-Hans': '安哥拉', 'yue-Hant': '安哥拉', 'zgh': 'ⴰⵏⴳⵓⵍⴰ', 'zh': '安哥拉', 'zh-Hans': '安哥拉', 'zh-Hant': '安哥拉', 'zu': 'i-Angola'},
'AQ': {'af': 'Antarktika', 'am': 'አንታርክቲካ', 'ar': 'أنتاركتيكا', 'as': 'এণ্টাৰ্কটিকা', 'ast': 'L’Antártida', 'az': 'Ant... | Python | 1 |
izing when calling `sep_by`, `sep_by1::<Vec<_>, _, _>(...)`.
///
/// ```
/// # extern crate combine;
/// # use combine::*;
/// # use combine::parser::char::digit;
/// # use combine::stream::easy;
/// # use combine::stream::state::{State, SourcePosition};
/// # fn main() {
/// let mut parser = sep_end_by1(digit(), token... | Rust | 0 |
let mut table = Table::default();
let p1 = page::Pointer {
cksum: 7,
.. Default::default()
};
let p2 = page::Pointer {
cksum: 7,
cluster: cluster::Pointer::new(100).unwrap(),
.. Default::default()
};
table.inse... | Rust | 0 |
from langchain.retrievers import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import CrossEncoderReranker
from langchain_community.cross_encoders import HuggingFaceCrossEncoder
from langchain_huggingface.embeddings import HuggingFaceEmbeddings
def rerank_docs(user_question, retriever,... | Python | 1 |
=> {
let ord = l.as_str().to_uppercase();
if ord == "ASC" || ord == "DESC" {
ord
} else {
"ASC".to_owned()
}
}
None => "DESC".to_owned(),
};
let order_string = format!(
" ORDER BY (object #> ($2)::text[]) {... | Rust | 0 |
def rotate_matrix_in_place(matrix):
n = len(matrix)
if n == 0 or n != len(matrix[0]): return
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix: row.reverse()
def run_tests():
tests = {
"3x3": ([[1,2,3],[4,5... | Python | 1 |
ise self.skipTest("not supported")
self.assert_stdout('procsmem.py', stderr=DEVNULL)
def test_killall(self):
self.assert_syntax('killall.py')
def test_nettop(self):
self.assert_syntax('nettop.py')
def test_top(self):
self.assert_syntax('top.py')
def test_iotop(self):
... | Python | 1 |
# streamlit_app/app.py
import streamlit as st
import requests
st.set_page_config(page_title="E-Commerce Recommender", layout="centered")
st.title(" Product Recommendation Engine")
st.write("Enter a user ID to get personalized product recommendations.")
# Input form
user_id = st.number_input("User ID", min_value=0, ... | Python | 1 |
, cv_PtrOfCUDA_NvidiaOpticalFlow_2_0_get_inner_ptr_mut
}
impl PtrOfCUDA_NvidiaOpticalFlow_2_0 {
#[inline] pub fn as_raw_PtrOfCUDA_NvidiaOpticalFlow_2_0(&self) -> *const c_void { self.as_raw() }
#[inline] pub fn as_raw_mut_PtrOfCUDA_NvidiaOpticalFlow_2_0(&mut self) -> *mut c_void { self.as_raw_mut() }
}
impl... | Rust | 0 |
#!/usr/bin/env pythonw
from Carbon.Cm import OpenDefaultComponent
from CarbonX.OSA import OSAComponentInstance
from CarbonX.kAE import *
from CarbonX.kOSA import *
from CarbonX.AE import *
from aem import Codecs, Application
codecs = Codecs()
osac = OSAComponentInstance(OpenDefaultComponent('osa ', 'ascr'))
scriptD... | Python | 1 |
await;
if let Err(err) = res {
// This instance of WaitAsync can return one of two errors:
// - InvalidAddress: Someone did something silly with
// memory.
// - InvalidHandle: Shouldn't happen since we hold the
// ServerPor... | Rust | 0 |
expect("mutex").next() {
info!("NEXT");
warp::reply::json(&status)
} else {
panic!("NEXT")
}
});
// POST /prev => { .. song status .. }
let prev = warp::post().and(warp::path!("prev")).map(move || {
if let Ok(status) = controls.lock().expect("mute... | Rust | 0 |
from falcor import *
def render_graph_PathTracer():
g = RenderGraph("PathTracer")
PathTracer = createPass("PathTracer", {'samplesPerPixel': 1})
g.addPass(PathTracer, "PathTracer")
VBufferRT = createPass("VBufferRT", {'samplePattern': 'Stratified', 'sampleCount': 16, 'useAlphaTest': True})
g.addPass... | Python | 1 |
model
Deleted,
#[allow(missing_docs)] // documentation missing in model
DeleteFailed,
#[allow(missing_docs)] // documentation missing in model
DeleteInProgress,
#[allow(missing_docs)] // documentation missing in model
Ready,
/// Unknown contains new variants that have been added since th... | Rust | 0 |
import logging
import urlparse
from spiro.task import Task
from .base import Step
"""
Instead of handling 30X redirects as a HTTP case, we're handling them in the
response pipeline.
"""
class ScheduleUrls(Step):
def __init__(self, settings, work_queue=None, user_settings=None, **kwargs):
"""Initialzation"... | Python | 1 |
alizer {
symmetry_visualizer: SymmetryVisualizer::new(),
}
}
fn post_setup(&mut self, program_id: u32, framebuffer_id: u32) {
self.symmetry_visualizer.post_setup(program_id, framebuffer_id);
}
fn update(&mut self, audio_frame: audio::AudioFrame) {
self.symmetry_visu... | Rust | 0 |
import pytest
from zabbix_get import zabbix_get
class TestModbusShort(object):
# test coils(bits)
def test_modbus_datatype_short_bit_0(self, host):
key = "modbus_read["+host+",1,1,1,b]"
assert zabbix_get(key) == '1'
# 16bit, all tests are PDU (start from 0 address)
# INT16,Big Endia... | Python | 1 |
from discord.ext import commands
class QuotientError(commands.CheckFailure):
pass
class NotSetup(QuotientError):
def __init__(self):
super().__init__(
"This command requires you to have Quotient's private channel.\nKindly run `{ctx.prefix}setup` and try again."
)
class NotPremi... | Python | 1 |
, Copy, Debug, PartialEq, Default, PointType)]
pub struct LasPointFormat6 {
#[pasture(BUILTIN_POSITION_3D)] pub position: Vector3<f64>,
#[pasture(BUILTIN_INTENSITY)] pub intensity: u16,
#[pasture(BUILTIN_RETURN_NUMBER)] pub return_number: u8,
#[pasture(BUILTIN_NUMBER_OF_RETURNS)] pub number_of_returns: ... | Rust | 0 |
from transformers import Qwen2ForCausalLM, Qwen2Config
import torch
import sys
sys.path.append("..")
from rope_patch.qwen2_rope_patch import patch_qwen2_rope_scaling
# conf = Qwen2Config(
# hidden_size=160,
# intermediate_size=100,
# num_hidden_layers=2,
# num_attention_heads=8,
# num_key_value_h... | Python | 1 |
RecvMaxSize, transport::tcp::NoDelay,
transport::tcp::KeepAlive,
transport::tls::CaFile,
transport::tls::CertKeyFile,
transport::websocket::RequestHeaders];
}
impl Drop for DialerOptions
{
fn drop(&mut self)
{
// Closing the dialer should only ever result in success... | Rust | 0 |
Config::default())
.map(|(p, m), _| (p, StreamMuxerBox::new(m)))
.map_err(|e| -> io::Error { panic!("Failed to create transport: {:?}", e); })
.boxed();
let local_id = local_public_key.clone().into_peer_id();
let store = MemoryStore::new(local_id.clone());
le... | Rust | 0 |
|', ' ', ' ', ' '] {
'0'
} else if input[..] == [' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', '|', ' ', ' ', ' '] {
'1'
} else if input[..] == [' ', '_', ' ', ' ', '_', '|', '|', '_', ' ', ' ', ' ', ' '] {
'2'
} else if input[..] == [' ', '_', ' ', ' ', '_', '|', ' ', '_', '|', ' ', ' ', ... | Rust | 0 |
# Don't shuffle excluded or invalid Death Wishes
if not world.is_dlc2() and name == "Snatcher Coins in Nyakuza Metro" or world.is_dw_excluded(name):
continue
dw_list.append(name)
world.random.shuffle(dw_list)
count = world.random.randint(world.options.DWSh... | Python | 1 |
&syn::parse_str(riko_core::util::SAMPLE_CREATE_REACTOR).unwrap(),
)
.unwrap()
.unwrap();
let actual = expand_ir(&src).unwrap().into_token_stream().to_string();
let expected = quote! {
#[no_mangle]
#[allow(clippy::useless_conversion)]
... | Rust | 0 |
8,
intrinsics::ctpop8,
intrinsics::ctlz8,
intrinsics::cttz8,
bswap8)
int_impl!(u16, 16,
intrinsics::ctpop16,
intrinsics::ctlz16,
intrinsics::cttz16,
intrinsics::bswap16)
int_impl!(u32, 32,
intrinsics::ctpop32,
intrinsics::ctlz32,
intrinsics::cttz32,
intrinsics::bswap32)... | Rust | 0 |
0,
max_actor_speed: 10.0,
}
}
}
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize, PartialEq)]
pub struct PlayerId(pub u64);
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct Player {
pub id: PlayerId,
pub active: bool,
pub name: String,
pub actor... | Rust | 0 |
match cow {
Cow::Borrowed(_) => unreachable!(),
Cow::Owned(s) => {
assert_eq!(s, "abc\u{20AC}\u{FFFD}\u{00E4}");
}
}
assert_eq!(encoding, WINDOWS_1257);
assert!(had_errors);
}
#[test]
fn test_decode_ascii_only_windows_1257... | Rust | 0 |
# =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
# ... | Python | 1 |
One char too long values:
self.assertRaises(ValueError, setattr, cs, "value", "1234567")
## def test_perf(self):
## check_perf()
try:
c_wchar
except NameError:
pass
else:
class WStringTestCase(unittest.TestCase):
def test_wchar(self):
c_wchar(u"x")
repr(by... | Python | 1 |
let mut line = String::new();
return match self.reader.read_line(&mut line) {
// End of file
Ok(0) => None,
Ok(_) => {
//println!("line = {:?}", line);
// TODO: alert when we don't succeed at parsing
TaskUpdate::from_str(&line)... | Rust | 0 |
# Copyright (c) Facebook, Inc. and its affiliates.
from . import DensePoseChartConfidencePredictorMixin, DensePoseChartPredictor
from .registry import DENSEPOSE_PREDICTOR_REGISTRY
@DENSEPOSE_PREDICTOR_REGISTRY.register()
class DensePoseChartWithConfidencePredictor(
DensePoseChartConfidencePredictorMixin, DensePo... | Python | 1 |
5);
assert_eq!(vec, [1, 4, 2, 3, 5]);
}
#[test]
#[should_panic]
fn insert_already_full() {
let mut vec = StaticVec::<i32, 5>::from([1, 2, 3, 4, 5]);
vec.insert(1, 4);
}
#[test]
#[should_panic]
fn insert_index_too_high() {
let mut vec = StaticVec::<i32, 8>::from([1, 2, 3, 4, 5]);
vec.insert(19, 4);
}
#[tes... | Rust | 0 |
currency_code: holding.purchase_price.currency.code(),
}),
purchase_date: match &holding.purchase_date {
Some(date) => Some(date.format(DATE_FMT).to_string()),
_ => None,
}
},
... | Rust | 0 |
fn canonical_name(&self) -> &str {
COCKROACHDB_SOURCE_NAME
}
fn connector(&self) -> &'static dyn Connector {
SqlDatamodelConnectors::POSTGRES
}
}
pub struct PostgresDatasourceProvider;
impl DatasourceProvider for PostgresDatasourceProvider {
fn is_provider(&self, provider: &str) -... | Rust | 0 |
reset_query_pool(
&mut self,
_pool: &n::QueryPool,
_queries: Range<query::QueryId>,
) {
// Nothing to do here
// vkCmdResetQueryPool sets the queries to `unavailable` but the specification
// doesn't state an affect on the `active` state. Every queries at the end of ... | Rust | 0 |
));
let int_ctrl = AutoInterruptController::new();
let mut core = ConfiguredCore::new_with(mem.rom.entry_point(), int_ctrl, mem);
core.dar[STACK_POINTER_REG] = core.mem.rom.stack_pointer();
Megadrive {
core,
gfx: Gfx::new(),
}
}
pub fn step_n(... | Rust | 0 |
let data = self.get_row_from_point()?;
self.scanner.set_seek_key(None);
self.cursor += 1;
if data.is_some() {
return Ok(data);
}
continue;
}
let data = self.get_row_from_range()?;
if ... | Rust | 0 |
_base_ = [
'../_base_/models/upernet_crossformer.py',
'../_base_/datasets/ade20k_swin.py',
'../_base_/default_runtime.py',
'../_base_/schedules/schedule_160k.py'
]
model = dict(
pretrained=None,
backbone=dict(type='CrossFormer_L', group_size=[7, 7, 7, 7], crs_interval=[8, 4, 2, 1],
ini... | Python | 1 |
from .models import Medication, MedicationLog
from django.shortcuts import get_object_or_404
def delete_medication(medication):
medication.delete()
def log_medication(user, medication, date, time_taken, dose_index):
log = MedicationLog.objects.create(
user=user,
medication=medication,
... | Python | 1 |
import requests,argparse,sys,re
from multiprocessing.dummy import Pool
requests.packages.urllib3.disable_warnings()
def banner():
text = """██╗ ██╗██╗ ██╗ ██╗ ██╗██╗ ██╗
██║ ██║██║ ██║ ██║ ██║██║ ██║
██║ █╗ ██║██║ ██║ ███████║██║ ██║
██║███╗██║██║ ██║ ██╔══██║██║ ... | Python | 1 |
'n_clicks')],
prevent_initial_call=True
)
def handle_bulk_selection(select_all, clear_all, common):
"""處理批量選擇操作"""
ctx_id = ctx.triggered[0]['prop_id'].split('.')[0]
if ctx_id == 'btn-select-all':
return [[True] * len(INDICATOR_CONFIG)]
elif ctx_id == 'btn-clear-all':
return [[... | Python | 1 |
import aerosandbox as asb
import aerosandbox.numpy as np
# Here, all distances are in meters and all angles are in degrees.
airplane = asb.Airplane(
name="Example Airplane",
xyz_ref=[0.5, 0, 0], # Reference for moments
s_ref=9, # Reference area
c_ref=0.9, # Reference chord
b_ref=10, # Reference... | Python | 1 |
import arrow
from collections import namedtuple
# ---------- Date & Time using Arrow ----------
# Get current UTC time
brewing_time = arrow.utcnow()
print(f"Current UTC brewing time: {brewing_time}")
# Convert brewing time to Europe/Rome timezone
brewing_time_rome = brewing_time.to("Europe/Rome")
print(f"Brewing time... | Python | 1 |
64_value()
.ok_or_else(make_schema_error)?;
term_buffer.set_i64(i64_val);
multifield_postings.subscribe(doc_id, term_buffer);
}
}
FieldType::F64(_) => {
for field_value in ... | Rust | 0 |
::new(buf_with_padding),
};
let read_rec = reader.read_record(0, expected_buf.len() as u64);
assert!(read_rec.is_err(), "Expected error, got {:?}", read_rec);
}
}
#[cfg(test)]
mod record_appender_tests {
use super::test_utils::*;
use super::*;
use bitrust_pb::BitRustDataRecord;
extern crate simp... | Rust | 0 |
manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'ggd-recipes', 'ggd-recipes Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
... | Python | 1 |
expected_output = {
"instance": {
"isp": {
"lsp_log": {
1: {
"count": 1,
"level": 1,
"received_timestamp": "00:02:36"},
2: {
"count": 1,
"level": 1,
... | Python | 1 |
(ret: Option<Spanned<Box<Expr>>>) -> Expr {
Expr::Ret(ret, TypeRef::invalid())
}
pub fn if_expr(if_expr: IfExpr) -> Expr {
Expr::IfExpr(if_expr, TypeRef::invalid())
}
pub fn while_expr(while_expr: WhileExpr) -> Expr {
Expr::WhileExpr(while_expr, TypeRef::invalid())
}
p... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
from koheron import command, connect
class Laser(object):
def __init__(self, client):
self.client = client
@command()
def start(self):
pass
@command()
def stop(self):
pass
@command()
def get_measu... | Python | 1 |
<&str>, a: Algorithm, ft: FingerprintType, f: &[u8]) {
assert!(parse(input.into_iter())
.map(|rd| rd == SSHFP::new(a, ft, f.to_vec()))
.unwrap_or(false));
}
test_parsing(
vec!["1", "1", "dd465c09cfa51fb45020cc83316fff21b9ec74ac"],
RSA,
SHA1,
&[
... | Rust | 0 |
ndex: usize,
layer_index: usize,
) -> NSEResult<Layer>;
fn finalize(&mut self) -> NSEResult<()>;
// Combine functions need to get `&mut self`, as they modify internal state of GPU buffers
fn combine_layer(&mut self, layer: &Layer, is_decode: bool) -> NSEResult<Layer> {
Ok(Layer(self.comb... | Rust | 0 |
.calendar_view(ID_VEC[0].as_str())
.calendar()
.event(ID_VEC[1].as_str())
.get_events();
assert_url_eq(
&client,
&format!(
"/me/calendarView/{}/calendar/events/{}",
ID_VEC[0], ID_VEC[1]
),
);
let client = graph();
client
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.