text string | label_name string | labels int64 |
|---|---|---|
def get_config():
class General:
log_frequency = 100
name = __name__.rsplit("/")[-1].rsplit(".")[-1]
batch_size_per_gpu = 3
fp16 = False
SeqDir = 'SemanticKITTI/dataset/sequences'
category_list = ['static', 'moving']
loss_mode = 'ohem'
K = 2
... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. 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 |
import pandas as pd
#SameRequirements as S1l; bop
# Get the CSV file
## Change location
csv_file = r"C:\Users\ArmandsPriede\OneDrive - Vidzemes Augstskola\Pitons\Data\signin_logs2.csv"
signin_logs_df = pd.read_csv(csv_file)
# Define substrings to match for each key field (Dictionary). Links file information to code
fi... | Python | 1 |
:?}", bt);
for line in btstr.lines() {
let line = String::from(line);
if begin == 0 && !loc.is_empty() && line.contains(&loc) {
// Underlined and magenta.
trace.push(format!("\x1F\x0313{}", line));
begi... | Rust | 0 |
e failure when exceeding max retries
call_count = 1
failure_count = 4
with pytest.raises(ValueError, match="Simulated failure on attempt 4"):
engine.evaluate()
# Test case for https://github.com/latchfield/vulcan-core/issues/76
def test_fact_insertion_iteration_matching():
# Test that rules th... | Python | 1 |
first = set(int(x) for x in input().split())
second = set(int(x) for x in input().split())
for _ in range(int(input())):
command, sequence, *data = input().split()
if command == "Add" and sequence == "First":
[first.add(int(x)) for x in data]
elif command == "Add" and sequence == "Second":
... | Python | 1 |
deModal(title=LocaleStr(key="gift_code_modal.title"))
modal.translate(self.view.locale)
await i.response.send_modal(modal)
timed_out = await modal.wait()
if timed_out:
return
codes = (
modal.code_1.value,
modal.code_2.value,
modal... | Python | 1 |
ax.grid()
plt.plot(tm[0:i],Q1s[0:i],'r-',label=r'$Q_1$')
plt.plot(tm[0:i],Q2s[0:i],'b:',label=r'$Q_2$')
plt.ylabel('Heaters')
plt.xlabel('Time (sec)')
plt.legend(loc='best')
plt.draw()
plt.pause(0.05)
# Turn off heaters and close connection
a.Q1(0)
... | Python | 1 |
::{Aes, Key as AesKey};
pub mod clocks;
pub use clocks::ClockRequirements;
pub mod pins;
pub use pins::{
Pin,
Pins,
};
pub mod flash;
pub use flash::FlashGordon;
pub mod gint;
pub use gint::GroupInterrupt;
pub mod i2c;
pub use i2c::I2cMaster;
pub mod pwm;
pub use pwm::Pwm;
pub mod spi;
pub use spi::SpiMa... | Rust | 0 |
import os
import pickle
import tempfile
import arrow
from dotenv import load_dotenv
from openai import OpenAI
from pinecone import Pinecone
from tools.vision import vision_completion
from unstructured.chunking.title import chunk_by_title
from unstructured.cleaners.core import clean, group_broken_paragraphs
from unstru... | Python | 1 |
# Exception Handling in Python
try:
# Prompt the user to enter two numbers
a = input("Enter a number: ")
b = input("Enter another number: ")
# Attempt to perform division and display the result using an f-string
print(f"{a} / {b} = {int(a) / int(b)}")
except ZeroDivisionError:
# Handl... | Python | 1 |
clone = type(self)()
clone._copy_from(self)
return clone
def iteritems(self):
"""Iterate over all header lines, including duplicate ones."""
for key in self:
vals = self._container[key.lower()]
for val in vals[1:]:
yield vals[0], val
... | Python | 1 |
new_all_txt = [" ".join(new_all_txt)]
try:
x = count.fit_transform(new_all_txt)
bow = x.toarray()[0]
max_possible_entropy = np.log(num_word)
e = entropy(bow)
redundancy = (1 - e / max_possible_entropy)
... | Python | 1 |
105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac").unwrap()),
}],
lock_time: 0,
};
Block {
header,
txns: vec![tx],
}
}
... | Rust | 0 |
ant(Shape)]
enum ShapeEnumShapeBound {
Circle { x: i32, y: i32 },
Rectangle(Rectangle, Rectangle),
}
fn main() {}
<gh_stars>0
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - UHCI_CONF0"]
pub uhci_conf0: UHCI_CONF0,
#[doc = "0x04 - UHCI_INT_RAW"]
pub uhci_int_raw: UHCI... | Rust | 0 |
).into()))
}
#[inline(always)]
fn to_slot(&self) -> GResult<Slot> {
Ok(Slot::$variant((*self).into()))
}
}
);
}
impl_to_val_infallible!(i8, Int);
impl_to_val_infallible!(i16, Int);
impl_to_val_infallible!(i32, Int);
impl_to_val_infallible!(u8, Int);
impl_to_val_infallible!(u16, Int);... | Rust | 0 |
PostB1_5,
Post1_12,
}
pub mod msg;
pub mod log;
pub mod options;
pub mod points;
pub mod help;
//! Internal utility functions, types, and data structures.
/// Partition a mutable slice in-place so that it contains all elements for
/// which `predicate(e)` is `true`, followed by all elements for which
/// `predicat... | Rust | 0 |
call(py, (), None)
}
}
}
/// Calls a method on the object.
///
/// This is equivalent to the Python expression `self.name(*args, **kwargs)`.
pub fn call_method(
&self,
py: Python,
name: &str,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<... | Rust | 0 |
l', data=stage4, kernel=(7, 7), stride = (1, 1), pool_type='avg',
global_pool=True,
pooling_convention='valid', cudnn_off=False)
######## classifier ######
flatten = mx.symbol.Flatten(name='flatten', data=avg_pool)
classifier = mx.symbol.Full... | Python | 1 |
import numpy as np
def compute_mu(L_aug, Y, k, p):
"""Given label matrix L_aug and labels Y, compute the true mu params.
Args:
L: (np.array {0,1}) [n, d] The augmented (indicator) label matrix
Y: (np.array int) [n] The true labels in {1,...,k}
k: (int) Cardinality
p: (np.array... | Python | 1 |
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from plugin.models.base_model import Model
from plugin import util
class Stop(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
... | Python | 1 |
#!/usr/bin/env python
# Copyright (C) 2023- The University of Notre Dame
# This software is distributed under the GNU General Public License.
# See the file COPYING for details.
# This example shows TaskVine executing a dask graph using a wrapper
# to debug memory usage.
import ndcctools.taskvine as vine
import argp... | Python | 1 |
@mock.patch(
'deeplite_torch_zoo.api.datasets.classification.imagenet.create_dataset',
MockedPath)
@mock.patch(
'deeplite_torch_zoo.api.datasets.classification.imagenet.create_loader',
create_loader)
def test_unit_imagenet(*args):
get_imagenet('')
| Python | 1 |
try:
cache[stream] = rv
except Exception:
pass
return rv
return func
_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin)
_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)
_default_text_stderr = _make_c... | Python | 1 |
from collections import deque
def bfs(parent, source, sink, graph):
# create variables visited and make a queue
visited = [False] * (sink + 1)
# insert the sink node to the queue
queue = deque([source])
visited[source] = True
while queue:
# get the node from the queue
node = qu... | Python | 1 |
always)]
pub fn tmra5trig(&self) -> TMRA5TRIG_R {
TMRA5TRIG_R::new(((self.bits >> 7) & 0x0f) as u8)
}
#[doc = "Bits 0:6 - Counter/Timer A5 Pattern Limit Count."]
#[inline(always)]
pub fn tmra5lmt(&self) -> TMRA5LMT_R {
TMRA5LMT_R::new((self.bits & 0x7f) as u8)
}
}
impl W {
#[... | Rust | 0 |
start_date = (datetime.now() - timedelta(days=365)).strftime("%Y-%m-%d")
# 获取股票数据
stock_df = active_data_source.get_historical_k_data(
code=code,
start_date=start_date,
end_date=end_date,
frequency="d",
... | Python | 1 |
= V8::Exception_Error(error_string.into());
Isolate::raw().as_mut().unwrap().ThrowException(exception);
}
}
pub fn throw_type_error(error_string: &str) {
unsafe {
let error_string = V8::String::new_from_slice(error_string);
let exception = V8::Exception_TypeE... | Rust | 0 |
oken");
if let Some(var_269) = &input.next_token {
scope_268.string(var_269);
}
#[allow(unused_mut)]
let mut scope_270 = writer.prefix("MaxRecords");
if let Some(var_271) = &input.max_records {
scope_270.number(
#[allow(clippy::useless_conversion)]
aws_smithy_... | Rust | 0 |
() -> !; }
<reponame>luisonthekeyboard/buddhasay<filename>src/main.rs
use rand::Rng;
use std::fs::File;
use std::io::prelude::*;
#[macro_use]
extern crate serde_derive;
const WRAP_INDEX: usize = 37;
const BUDDHA: [&str; 7] = [
" \\",
" \\ ___",
" \\ (-_-) ",
" _) (_ ",
" / \\",... | Rust | 0 |
GenerationV1::describe_system(&toplevel)?,
);
}
}
Ok(toplevelspec)
}
fn describe_system(generation: &Path) -> Result<GenerationV1> {
let generation = generation
.canonicalize()
.map_err(|e| format!("Failed to canoni... | Rust | 0 |
import pytest
from tests import assert_result_within_score_range
from presidio_analyzer.predefined_recognizers import UsSsnRecognizer
@pytest.fixture(scope="module")
def recognizer():
return UsSsnRecognizer()
@pytest.fixture(scope="module")
def entities():
return ["US_SSN"]
@pytest.mark.parametrize(
... | Python | 1 |
import argparse
import torch
from diffusers import AutoPipelineForText2Image
from onediff.quantization.quantize_pipeline import QuantPipeline
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--floatting_model_path", default="runwayml/stable-diffusion-v1-5"
)
parser.... | Python | 1 |
from ursina import Shader
camera_empty_shader = Shader(
vertex='''
#version 430
in vec4 p3d_Vertex;
uniform mat4 p3d_ViewMatrixInverse;
in vec2 p3d_MultiTexCoord0;
out vec2 uv;
void main() {
gl_Position = p3d_ViewMatrixInverse * p3d_Vertex;
uv = p3d_MultiTexCoord0;
}
''',
fragment='''
#version 430
unifor... | Python | 1 |
# -*- coding: utf-8 -*-
"""
字体管理模块
统一处理字体查找、文本创建和字体降级策略
"""
import os
import sys
import platform
from typing import Optional, List
from moviepy import TextClip
from config import get_user_data_dir
class FontManager:
"""字体管理器"""
def __init__(self):
self._cached_font_path = None
self._font... | Python | 1 |
::BOOL>;
#[doc = "*Required features: 'Win32_System_ApplicationInstallationAndServicing', 'Win32_Foundation'*"]
#[cfg(feature = "Win32_Foundation")]
pub type LPEVALCOMCALLBACK = ::core::option::Option<unsafe extern "system" fn(istatus: STATUSTYPES, szdata: super::super::Foundation::PWSTR, pcontext: *mut ::core::ffi::c_... | Rust | 0 |
s::PooledConn;
use crate::core::errors::AppError;
use crate::core::requests::UpdateOrderData;
use crate::db::schema::orders;
#[derive(Clone, Serialize, Deserialize, Insertable, AsChangeset)]
#[table_name="orders"]
pub struct OrderUpdate {
pub status_code: i32,
#[serde(skip)] pub update_date: Option<NaiveDat... | Rust | 0 |
/// Right mouse button is down
pub right_mouse: bool,
/// Shift key is down
pub shift: bool,
/// First x button is down
pub xbutton1: bool,
/// Second x button is down
pub xbutton2: bool,
/// Control key is down
pub control: bool,
}
impl Into<usize> for KeyMouseState {
... | Rust | 0 |
Debug, TryFromPrimitive)]
#[repr(u8)]
pub enum CartridgeType {
RomOnly = 0x00,
Mbc1 = 0x01,
Mbc1Ram = 0x02,
Mbc1RamBattery = 0x03,
Mbc2 = 0x05,
Mbc2Battery = 0x06,
RomRam = 0x08,
RomRamBattery = 0x09,
Mmm01 = 0x0B,
Mmm01Ram = 0x0C,
Mmm01RamBattery = 0x0D,
Mbc3TimerBatter... | Rust | 0 |
MacCall(mac) => mac.tokens.as_ref(),
}
}
fn tokens_mut(&mut self) -> Option<&mut Option<LazyTokenStream>> {
match self {
StmtKind::Local(local) => Some(&mut local.tokens),
StmtKind::Item(item) => item.tokens_mut(),
StmtKind::Expr(expr) | StmtKind::Semi(expr) =... | Rust | 0 |
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
nums.sort()
dp = [[num] for num in nums]
res = []
for i in range(len(nums)-1,-1,-1):
for j in range(i+1, len(nums)):
if nums[j] % nums[i] == 0:
temp = [nums... | Python | 1 |
LiveryScanner().scan_mods_path(str(tmp_path / "nonexistent"))
scan_liveries_mock.assert_not_called()
def test_scan_campaign_livery_directory(
tmp_path: Path, scan_liveries_mock: Mock
) -> None:
paths = [
tmp_path / "foo/Liveries",
tmp_path / "bar",
tmp_path / "baz/Liveries",
]
... | Python | 1 |
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
from typing import Dict
from .service import paraphrase
router = APIRouter()
class ParaphraseRequest(BaseModel):
text: str = Field(..., min_length=3)
model_name: str = Field("t5", description="t5 | bart | custom HF repo")
l... | Python | 1 |
feature extraction
if extract_features:
feature_module = block.feature_module(extract_features)
if feature_module:
feature_module = 'blocks.{}.{}.'.format(stage_idx, block_idx) + feature_module
feature_channels = block.... | Python | 1 |
pool_0: pool_0_increment,
currency_1: trading_pair.second(),
pool_1: pool_1_increment,
share_increment,
});
if currency_id_a == trading_pair.first() {
Ok((pool_0_increment, pool_1_increment, share_increment))
} else {
Ok((pool_1_increment, pool_0_increment, share_increment))
}... | Rust | 0 |
mut InterruptStackFrame) {
static KEYBOARD: Lazy<Mutex<Keyboard<layouts::Us104Key, ScancodeSet1>>> = Lazy::new(|| {
Mutex::new(Keyboard::new(
layouts::Us104Key,
ScancodeSet1,
HandleControl::Ignore,
))
});
let mut keyboard = KEYBOARD.lock();
let mut po... | Rust | 0 |
#[cfg(not(feature = "no-slow-safety-checks"))]
macro_rules! rendy_with_slow_safety_checks {
($($tt:tt)*) => { $($tt)* };
}
/// Resolve into input AST if rendy is requested to perform slow safety checks.
#[macro_export]
#[cfg(feature = "no-slow-safety-checks")]
macro_rules! rendy_with_slow_safety_checks {
($($... | Rust | 0 |
*self == TCM_WWAIT_EN_A::TCM_WWAIT_EN_0
}
#[doc = "Checks if the value of the field is `TCM_WWAIT_EN_1`"]
#[inline(always)]
pub fn is_tcm_wwait_en_1(&self) -> bool {
*self == TCM_WWAIT_EN_A::TCM_WWAIT_EN_1
}
}
#[doc = "Write proxy for field `TCM_WWAIT_EN`"]
pub struct TCM_WWAIT_EN_W<'a> {
... | Rust | 0 |
x07"),
'b' => Some("\x08"),
'f' => Some("\x0c"),
'v' => Some("\x0b"),
'&' => Some(""),
_ => None,
}
}
named!(string_escape_numeric<&str, char>, map_opt!(alt!(
preceded!(tag("x"), digits!(u32, 16)) |
preceded!(tag("o"), digits!(u32, 8)) |
digits!(u32, 10)
), ::std... | Rust | 0 |
import sensor
import image
import lcd
import time
lcd.init(freq=15000000)
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.run(1)
green_threshold = (0, 80, -70, -10, -0, 30)
while True:
img=sensor.snapshot()
blobs = img.find_blobs([green_threshold])
if ... | Python | 1 |
'//div[@class="fe-proposal-additional-details additonal-details"]')
ans = self.chatgpt_get(self.data["OPENAI_USER_ROLE"])
helper.type_text(additional_details, ans, By.XPATH, './div/section/div//textarea')
ques_area = helper.ensure_find_element(additional_details, By.XPATH, './div/section/div[2]'... | Python | 1 |
set;
}
// VIOT
if let Some((iommu_bdf, devices_bdf)) = device_manager.lock().unwrap().iommu_attached_devices()
{
let viot = create_viot_table(iommu_bdf, devices_bdf);
let viot_offset = prev_tbl_off.checked_add(prev_tbl_len).unwrap();
guest_mem
.write_slice(viot.as_s... | Rust | 0 |
", 0, num_syms);
for sym in symbols.iter() {
let day_format = date.clone();
let sym = sym.clone();
let trades_day = Arc::clone(&trades);
let mut client = client.clone();
let counter = counter.clone();
thread_pool.execute(move || {
// Retry up to 50 times
for j in 0..50 {
ma... | Rust | 0 |
ype, Copy, Clone)]
pub(crate) enum EthereumValueKind {
Address,
FixedBytes,
Bytes,
Int,
Uint,
Bool,
String,
FixedArray,
Array,
Tuple,
}
impl EthereumValueKind {
pub(crate) fn get_kind(token: ðabi::Token) -> Self {
match token {
ethabi::Token::Address(_... | Rust | 0 |
own superhero capes or masks, and organize superhero-themed games and challenges.
8. Outdoor Adventure: Plan an outdoor adventure party at a local park or nature reserve. Arrange activities like hiking, nature scavenger hunts, or a picnic with games. Encourage exploration and appreciation for the outdoors.
Remember to... | Python | 1 |
ibbles) -> Result<(Nibbles, Nibbles)> {
match get_length_in_nibbles(nibbles) > 0 {
false => Ok((EMPTY_NIBBLES, EMPTY_NIBBLES)),
true => get_nibble_at_index(nibbles, 0).and_then(|first_nibble| {
Ok((
get_nibbles_from_offset_bytes(vec![first_nibble]),
slice_... | Rust | 0 |
test]
fn test_input_focus() {
use super::super::Input;
let e: Event = Input::Focus(false).into();
let x: Option<Event> = FocusEvent::from_focused(true, &e);
let y: Option<Event> = x
.clone()
.unwrap()
.focus(|focused| FocusEvent::from_focused(focu... | Rust | 0 |
def test_stable_diffusion_panorama_intermediate_state(self):
number_of_steps = 0
def callback_fn(step: int, timestep: int, latents: torch.Tensor) ->None:
callback_fn.has_been_called = True
nonlocal number_of_steps
number_of_steps += 1
if step == 1:
latents = latents.... | Python | 1 |
# 在目标Excel中查找商品名称列和SKU编码列
target_product_name_column = None
target_sku_column = None
for col in target_df.columns:
# 查找商品名称列
if '商品名称' in str(col):
target_product_name_column = col
n... | Python | 1 |
groupfs样式的语法,如果需要,但容器运行时可以将其转换为systemd语义
// 获取 linux下cgroup_parent
let pod_sandbox_config_linux_cgroup_parent = pod_sandbox_config_linux.cgroup_parent;
// LinuxSandboxSecurityContext包含沙盒安全属性
// 获取 linux下security_context
let pod_sandbox_config_linux_security_context = match pod_s... | Rust | 0 |
import time
import cv2
import torch
from models.fatigue_monitor import SleepDetector
from models.pose_estimator import AlphaPoseEstimator
from models.yolo_detector import YoloV5Detector
from utils.vis import draw_keypoints136
yolov5_weight = './weights/yolov5s.torchscript.pt'
alphapose_weight = './weights/halpe136_m... | Python | 1 |
hape operation
ShapeSet = 0
ShapeUnion = 1
ShapeIntersect = 2
ShapeSubtract = 3
ShapeInvert = 4
XShapeCombineRegion = _lib.XShapeCombineRegion
XShapeCombineRegion.argtypes = [
POINTER(Display),
c_void_p,
ctypes.c_int, # shape kind
ctypes.c_int, ctypes.c_int, # x, y offset
c_void_p,
ctypes.c_i... | Python | 1 |
ted_list = sorted(lists[list_name], key=lambda x: x["votes"], reverse=True)
list_content = '\n'.join([f"{i+1}. {entry['item']} - Votes: {entry['votes']}" for i, entry in enumerate(sorted_list)])
await send_embed_message(message.channel, "List Display",
f"**{list_name}**\... | Python | 1 |
trace("READ\tarr[{".to_string() + &index.to_string() + "}]", data);
trace("READ\tarr[{".to_string() + &pivot.to_string() + "}]", data);
trace("WRITE\tarr[{".to_string() + &index.to_string() + "}]", data);
trace("WRITE\tarr[{".to_string() + &pivot.to_string() + "}]", data);
arr.swap(index as usize, pivot... | Rust | 0 |
eers: &AdnlPeers) -> Result<QueryResult> {
log::warn!(
target: TARGET,
"try_consume_query OVERLAY {:?} from {}",
object,
peers.other()
);
Ok(QueryResult::Rejected(object))
}
async fn try_consume_query_bundle(
&self,
mut obj... | Rust | 0 |
expr,)*];
data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr,)*] ),* ];
) => (
fields!( control fields: [ $($ctag => $cdata,)* ];
data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; )
);
(
control fields: [$($ctag:expr => $cdata:... | Rust | 0 |
), 3);
assert_eq!(Solution::unique_paths(7, 3), 28);
assert_eq!(Solution::unique_paths(3, 3), 6);
}
}
<filename>src/messaging/controls.rs<gh_stars>1-10
pub mod message;
pub mod metadata;
use hreq::prelude::*;
use hreq::Error;
mod common;
#[test]
fn code_302() -> Result<(), Error> {
common::set... | Rust | 0 |
from opencompass.openicl.icl_prompt_template import PromptTemplate
from opencompass.openicl.icl_retriever import ZeroRetriever
from opencompass.openicl.icl_inferencer import GenInferencer
from opencompass.datasets import MBPPDataset, MBPPEvaluator
mbpp_reader_cfg = dict(input_columns=["text", "test_list"], output_colu... | Python | 1 |
)
.required(true),
),
).subcommand(
// this is a fake subcommand - it's used in conjunction with
// AppSettings:AllowExternalSubcommand to treat it as an
// entry point script
SubCommand::with_name("<script>").about("Script to run"),
)
}
#[cfg_attr(feature = "cargo-c... | Rust | 0 |
x.mode,
}
}
pub fn get_fun_kind(&self) -> ast::FunKind {
match self {
Self::Borrowed(x) => x.fun.fun_kind,
Self::Counted(x) => x.fun_kind,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Method<'a> {
Borrowed(&'a ast::Method_),
Counted(Rc<Meth... | Rust | 0 |
read();
if !reg.dir().bit()
&& !reg.epeds().bit()
&& !reg.forcestall().bit()
&& !reg.txpktrdy().bit()
&& reg.eptype().is_ctrl()
{
break;
}
}
});
}
/// The UDP CSR register is a bit strange in... | Rust | 0 |
ath = SettingsRegistryPath::new(string)?;
Ok(self.join(path))
}
}
impl AsRef<SettingsRegistryPath> for &'_ SettingsRegistryPath {
fn as_ref(&self) -> &SettingsRegistryPath {
self
}
}
impl ToOwned for SettingsRegistryPath {
type Owned = SettingsRegistryPathBuf;
#[inline]
fn to_... | Rust | 0 |
from __future__ import annotations
def edit_distance(string_1: str, string_2: str, case_sensitive: bool = True) -> int:
"""
Calculates the minimum number of single-character edits required
to transform one string into another. Allowed operations are insertion,
deletion, and substitution.
Args:
... | Python | 1 |
import numpy as np
from pylab import figure, subplot, xlabel, ylabel, show
from math import sqrt, pi
import fluidfoam
#########################################
#
# Physical parameters
#
h = 0.01
U0 = 1.1
T0 = 4.0
viscof = 1e-6
delta = sqrt(viscof * T0 / pi)
# Loading OpenFoam results
#
mypath = "../laminar/"
#
# So... | Python | 1 |
e, 19) # left elbow IDX: 19
if 'left_hand' in handpose:
global_orient_hand_left = np.asarray(handpose["left_global_orient"]).reshape(3, 3)
left_wrist_global_rot = M @ global_orient_hand_left @ M # mirror switch
left_wrist_pose = np.linalg.inv(left_elbow_global_rot) @ left_wrist_global_rot... | Python | 1 |
from fastapi import APIRouter, Request
import db.sessions.admin_sessions.updates_func.applications as edit_applications
edit = APIRouter()
@edit.post("/name")
def _(id: int, value: str):
edit_applications.name(id, value)
@edit.post("/resource-url")
def _(id: int, value: str):
edit_applications.resource_url(i... | Python | 1 |
let mut f1 = std::fs::File::create("test1.dot").expect("create failed");
let mut f2 = std::fs::File::create("test2.dot").expect("create failed");
g1.to_dot(&mut f1, &settings, false).expect("can't fail");
g2.to_dot(&mut f2, &settings, false).expect("can't fail");
}
#[test]
fn test_diff_vis() {
let g1 =... | Rust | 0 |
es time)
xrange=linspace(0,1,Npixels_Test)
X0,X1=meshgrid(xrange,xrange)
test_batchsize=shape(X0)[0]*shape(X0)[1]
testsample=zeros([test_batchsize,2])
testsample[:,0]=X0.flatten()
testsample[:,1]=X1.flatten()
# parameters
eta=1.0
nsteps=10000
nskip_steps=100
batchsize=200
samples_count=0
costs=zeros(nsteps)
for j in... | Python | 1 |
is_none());
assert!(f2.peek().is_none());
}
// Completing the underlying future has no effect, because the value has not been `poll`ed in.
tx0.send(42).unwrap();
for _ in 0..2 {
assert!(f1.peek().is_none());
assert!(f2.peek().is_none());
}
// Once the Shared has been po... | Rust | 0 |
iebreaker_filled = True
for row in table.rows:
tiebreaker_value = row.cells[-3].content.value
if not tiebreaker_value or not tiebreaker_value.strip():
all_tiebreaker_filled = False
break
# Ustawianie miejsc i aktualizowanie widoku
... | Python | 1 |
("51", "Marne"),
("52", "Haute-Marne"),
("53", "Mayenne"),
("54", "Meurthe-et-Moselle"),
("55", "Meuse"),
("56", "Morbihan"),
("57", "Moselle"),
("58", "Nièvre"),
("59", "Nord"),
("60", "Oise"),
("61", "Orne"),
("62", "Pas-de-... | Python | 1 |
Predicted coordinates in the images.
"""
assert coords.shape[1] in (2, 4, 5)
assert len(center) == 2
assert len(scale) == 2
assert len(output_size) == 2
# Recover the scale which is normalized by a factor of 200.
scale = scale * 200.0
if use_udp:
scale_x = scale[0] / (output_si... | Python | 1 |
}
}
}
<gh_stars>0
//even fibonnacu numbers
fn fibonacci(n : i32) -> i32 {
let mut result: i32 = 2;
let mut fib3: i32 = 2;
let mut fib6: i32 = 0;
let mut sum : i32 = 0;
while result < n as i32 {
sum = sum + result;
result = 4*fib3 + fib6;
fib6 = fib3;
fib3 ... | Rust | 0 |
import pytest
import requests
from base_aux.base_types.m2_info import ObjectInfo
from base_aux.servers.m3_server2_fastapi import ServerFastApi_Thread
# =====================================================================================================================
class Test__Server_FastApi:
@classmethod
... | Python | 1 |
= delta)
if(sz):
avgLoadedAreaRatio/= sz
return avgLoadedAreaRatio
def defBackfillUniformLoads(self, trainModels, relativePositions, originSet, embankment, delta, eta= 1.0, gravityDir= xc.Vector([0, 0, -1])):
''' Define backfill loads due the uniform loads on the tracks.
... | Python | 1 |
# 4 - Sequência de Collatz:
# Crie um programa que solicite um número ao usuário e use um
# laço while para gerar e exibir a sequência de Collatz até chegar
# ao número 1.
n = float(input('Digite um numero: '))
while n > 1:
n += 1
if n % 2 == 0:
s
print() | Python | 1 |
attr.parse_args::<Meta>().ok())
.filter(|meta| meta.path().is_ident("name"))
.find_map(|meta| match meta {
Meta::NameValue(MetaNameValue {
lit: Lit::Str(lit), ..
}) => Some(lit.value().trim_matches('"').to_owned()),
_ => panic!... | Rust | 0 |
= torch.cat(all_spatial_sparsity_conv1_list, 0)
all_channel_sparsity_list = torch.cat(all_channel_sparsity_list, 0)
all_spatial_sparsity_conv3_list /= num_samples
all_spatial_sparsity_conv2_list /= num_samples
all_spatial_sparsity_conv1_list /= num_samples
all_channel_sparsity_list /= num_sampl... | Python | 1 |
#!/usr/bin/env python3
"""Debug admonition detection in detail."""
import sys
import re
from pathlib import Path
sys.path.insert(0, '.')
from asciidoc_dita_toolkit.modules.example_block import (
ExampleBlockDetector,
)
def debug_admonition_detection():
content = Path('tests/fixtures/ExampleBlock/ignore_adm... | Python | 1 |
Uri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap()));
read("hyper.rs", RequestUri::Authority("hyper.rs".to_owned()));
read("/", RequestUri::AbsolutePath("/".to_owned()));
}
use std::collections::HashMap;
fn main() {
let field_name = String::from("Favorite color");
let field_value = String::from("... | Rust | 0 |
nd(&mut self) {
self.first.visit_bsp_node_end();
self.second.visit_bsp_node_end();
}
}
#[derive(Copy, Clone)]
struct InternalWallQuad<'a> {
object_id: ObjectId,
sector: &'a WadSector,
seg: &'a WadSeg,
vertices: (Pnt2f, Pnt2f),
height_range: (WadCoord, WadCoord),
texture_name... | Rust | 0 |
"purplish_blue".into() => rgbf(0.108212525485730737262458, 0.153429608581970855496479, 0.344220218749182182982338),
"moderate_red".into() => rgbf(0.377697315249863829755839, 0.110432750805009693984005, 0.122840615085597376632265),
"purple".into() => rgbf(0.091322757592163850137723, 0.06232972802... | Rust | 0 |
Some((2, 3)));
mat!(match_basic_70, r"xxx", r"xxx", Some((0, 3)));
mat!(match_basic_71, r"(^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$)", r"feb 6,", Some((0, 6)));
mat!(match_basic_72, r"(^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$)", r"2/7", Some((0, 3)));
mat!(match_basic_73, r"(^|[ (,;])((... | Rust | 0 |
logger(get_test_identity(), full_buffer).unwrap();
let tag_properties = (0..MAX_TAGS as _)
.map(|tag_num| {
String::from_utf8(vec![('A' as c_char + tag_num) as u8; tag_len]).unwrap()
})
.collect::<Vec<_>>();
let mut builder = LogsDataBuilder::new(Buil... | Rust | 0 |
Some(TypedArena::new());
// Hopefully this unreachable! gets optimized out, because it should literally be
// unreachable.
let arena = match ctx.arena {
Some(ref mut arena) => arena,
None => unreachable!()
};
let ParseContext {string, ref mut stack, .. } ... | Rust | 0 |
#[clap(short = 'S', long, default_value_t = ArgColor { r: 63, g: 63, b: 116 })]
sky_color: ArgColor,
/// Color of the building borders.
#[clap(short, long, default_value_t = ArgColor { r: 0, g: 0, b: 0 })]
border_color: ArgColor,
/// Color of the building background.
#[clap(short = 'B', long,... | Rust | 0 |
::L, Phone::Rd],
J => &[Phone::J],
};
variations.add_phones(phones)
}
}
impl WriteOrthography for Sonorant {
fn orthography_fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.pad((*self).orthography())
}
}
impl WriteBroadPronunc for Sonorant {
fn broad_pronun... | Rust | 0 |
1.0,
) -> None:
"""Convert XYZ point cloud (e.g., multibeam sonar) into a gridded GeoTIFF using nearest-neighbor binning.
Assumes WGS84 UTM or projected coordinates in meters. Output uses a simple transform inferred
from the data extents.
"""
pts = np.loadtxt(xyz_path, usecols=[x_col, y_col, z_col... | Python | 1 |
modes
CENTRAL_CONTROL_MODE_MAP = {
"local": 0,
"air": 1,
"water": 2,
"total": 3,
}
# HVAC presets
PRESET_COMFORT = "comfort"
PRESET_ECO = "eco"
# DHW presets
PRESET_DHW_OFF = "off"
PRESET_DHW_HEAT_PUMP = "heat_pump"
PRESET_DHW_HIGH_DEMAND = "high_demand"
# System state values
SYSTEM_STATE_MAP = {
... | Python | 1 |
it can also accept a quoted string "hello world". I beleve we should accept 'a"hello"a',
and 'a"hello' as valid arguments.
*/
#[derive(Clone, Debug)]
pub struct StringArgumentPhrase(pub String);
impl ArgumentKind<CommandCtx> for StringArgumentPhrase {
type ParseError = StringArgumentPhraseParseError;
fn ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.