text
string
label_name
string
labels
int64
cfg, true), &net_cfg, &net.storage, false) .unwrap_or_else(|err| { warn!("Sync failed: {:?}", err) }); } <filename>src/busy.rs ///! Busy handler (when the database is locked) use std::convert::TryInto; use std::mem; use std::os::raw::{c_int, c_void}; use std::panic::catch_unwind; use std::ptr; use std::time::Du...
Rust
0
: usize, ) -> ImageInfoResult<ImageInfo> where R: BufRead + Seek { if length < 18 { return Err(ImageInfoError::UnrecognizedFormat); } let buffer = ri.read(length - 18, 18)?; if buffer.cmp(0, 18, b"TRUEVISION-XFILE.\x00") { if length < 18 + 16 { return Err(ImageInfoError::...
Rust
0
map1 = [ [3,3,5,3,1], [2,2,4,2,6], [4,9,2,3,4], [1,1,1,1,1], [3,3,5,9,2], ] dy = [-1,-1,1,1] dx = [-1,1,-1,1] def sum1(y, x) : total = 0 for i in range(4) : ny, nx = y+dy[i], x+dx[i] if 0 <= ny < 5 and 0 <= nx < 5 : total += map1[ny][nx] return total ...
Python
1
ans: bool = True, sample_name: str = "sample", feature_name: str = "feature", compute: bool = True, random_state: int | None = None, solver: str = "auto", solver_kwargs: dict = {}, **kwargs, ): super().__init__( n_modes=n_modes, ...
Python
1
`ENABLE`"] pub type ENABLE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ENABLE`"] pub struct ENABLE_W<'a> { w: &'a mut W, } impl<'a> ENABLE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the fie...
Rust
0
ns") if kwargs: raise ValueError(f"Unknown arguments: {', '.join(kwargs.keys())}") text = _normalize_unicode(text) tokens = tokenizer.encode_ordinary(text) output: list[tuple[str, dict]] = [] i = 0 while i < len(tokens): chunk_tokens = tokens[i :...
Python
1
["foo\n", "/*bar\nbaz*/", "\nqux"] assert strutils.split_special_areas("foo\n//bar\nbaz", [r"//.+$"]) == [ "foo\n", "//bar", "\nbaz", ] def test_escape_special_areas(): assert ( strutils.escape_special_areas('foo "bar" baz', ESCAPE_QUOTES, "*") == 'foo "bar" baz' ...
Python
1
from ofscraper.db.operations_.others import get_schema_changes def get_group_difference(model_id=None, username=None, db_path=None): changes = get_schema_changes(model_id=model_id, username=username, db_path=db_path) groupA = [ "media_hash", "media_model_id", "posts_model_id", ...
Python
1
ramdevice. pub fn open(&self) -> Result<zx::Channel, zx::Status> { struct UnownedFd(RawFd); impl AsRawFd for UnownedFd { fn as_raw_fd(&self) -> RawFd { self.0 } } // Safe because self.ramdisk is valid and the borrowed fd is not borrowed beyon...
Rust
0
"""PoE2游戏机制相关常量""" from typing import Dict, List, Set from enum import Enum class PoE2Constants: """PoE2核心游戏常量""" # 抗性相关 MAX_RESISTANCE = 80 # PoE2最大抗性80% BASE_CHAOS_RESISTANCE = -30 # 基础混沌抗性-30% # 能量护盾相关 ES_RECHARGE_DELAY = 2.0 # 能量护盾恢复延迟(秒) ES_RECHARGE_RATE = 0.3...
Python
1
use crate::message::HuobiMessage; #[derive(Serialize,Deserialize)] struct HuobiSubscription { id: Uuid, sub: String }// 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. use crate::{...
Rust
0
yout.setContentsMargins(10, 10, 10, 10) time_layout.setSpacing(20) time_group_box.setLayout(time_layout) return time_group_box def create_step_group_box(self): """ Create and configure the step setting group box Return: QGroupBox: A group box that contain...
Python
1
ssert_eq!(w.work, vec![]); assert_eq!(w.duplicates, vec![]); assert_eq!(w.duplicates, vec![]); } #[test] fn find_some_work_some_remaining_input_leaves_duplicates() { let mut input = vec![w_10(1), w_10(1), w_0(2), w_0(3), w_10(4), w_10(4), w_10(5)]; let w = find_work(&mut inp...
Rust
0
class Peta: def __init__(self): self.daftarKota = {} def printPeta(self): for kota in self.daftarKota: print(kota, ":", self.daftarKota[kota]) def tambahKota(self, kota): if kota not in self.daftarKota: self.daftarKota[kota] = [] return True ...
Python
1
'ema_updates': ema.updates if args.ema else 0, # 保存更新计数 'scaler': scaler.state_dict() if args.amp else None, 'best_acc': best_acc, }, filename) if is_best: logging.info(f"Saved ...
Python
1
&self, key: &str, map: F, default: O ) -> Result<O, Error> { self.attributes.get(key) .map(map) .unwrap_or(Ok(default)) // Error reporting here is done by what component is being resolved, rather than // where the attribute came from, for example a style file....
Rust
0
# 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: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or module...
Python
1
# This program takes the following input from the user, # Student's Name # Student's Roll No. # Marks in Maths # Marks in Physics # Marks in Chemistry # And provides a scorecard with their grades as output # With an added functionality of all the student records maintained in a json file import json # function to ret...
Python
1
t8\x10\x03\ \x12\n\n\x06kInt32\x10\x04*l\n\nDataLayout\x12\x11\n\rkYXDepthBatch\x10\ \0\x12\x11\n\rkYXBatchDepth\x10\x01\x12\x11\n\rkBatchYXDepth\x10\x02\x12\ \x11\n\rkBatchDepthYX\x10\x03\x12\x12\n\x0ekBatchDepthYX4\x10\x04*s\n\ \x0cFilterLayout\x12\x12\n\x0ekOutputInputYX\x10\0\x12\x12\n\x0ekOutputY\ ...
Rust
0
fn main() { let mut obj = RandomizedSet::new(); println!("{}", obj.insert(1)); println!("{}", obj.remove(2)); println!("{}", obj.insert(2)); println!("{}", obj.get_random()); println!("{}", obj.remove(1)); println!("{}", obj.insert(2)); println!("{}", obj.get_random()); } use secstr::Sec...
Rust
0
end, ) -> Result<ProcessingSession> { let mut sess = sess_builder.create(status)?; let result = sess.run(status); if let Err(e) = &result { if let ErrorKind::EngineError(engine) = e.kind() { let output = sess.get_stdout_content(); if output.is_empty() { tt_e...
Rust
0
class Gate(): def binaToInteger(self, binary): number = 0 for b in binary: number = (2 * number) + b return number def And(self, a, b): return a & b def AndBus(sef, al:list, bl:list): result = [] if(len(al) == len(bl)): for i in range(len(al)): result.append(al[i] ...
Python
1
import os import tifffile import torchvision.transforms as T from torchvision.datasets import ImageFolder from torchrs.transforms import ToTensor class EuroSATRGB(ImageFolder): """ Sentinel-2 RGB Land Cover Classification dataset from 'EuroSAT: A Novel Dataset and Deep Learning Benchmark for Land Use and La...
Python
1
t set a cookie on the top-level domain # NOTE: don't change this value; it's hard coded into various JavaScript files CSRF_COOKIE_NAME = 'esp_csrftoken' if SENTRY_DSN: # If SENTRY_DSN is set, send errors to Sentry via the Raven exception # handler. Note that our exception middleware (i.e., ESPErrorMiddleware) ...
Python
1
#[doc = "`read()` method returns [adc12mctl11::R](adc12mctl11::R) reader structure"] impl crate::Readable for ADC12MCTL11 {} #[doc = "`write(|w| ..)` method takes [adc12mctl11::W](adc12mctl11::W) writer structure"] impl crate::Writable for ADC12MCTL11 {} #[doc = "ADC12_B Memory Control 0 Register to ADC12_B Memor...
Rust
0
unts .entry((*x, y)) .and_modify(|c| *c += 1) .or_insert(1); } } for ((x1, y1), (x2, y2)) in rest { // According to problem constraint, slope will always be integral let slope = (y2 - y1) / (x2 - x1); let range = if x1 < x2 { *x1.....
Rust
0
= m.group(1) fontName = fontName.decode() else: fontName = None interpreter = PSInterpreter(encoding=encoding) interpreter.interpret(b"/Helvetica 4 dict dup /Encoding StandardEncoding put definefont pop") interpreter.interpret(data) fontdir = interpreter.dictstack[0]['FontDirectory'].value if fontName in fon...
Python
1
o) # Solve scale x /= dominate_ratio y /= dominate_ratio # Solve padding fh, fw = nh / dominate_ratio, nw / dominate_ratio x -= (fw - ow) / 2 y -= (fh - oh) / 2 return x, y def is_pos_out_of_bound(self, x, y): x, y = self.pixel_pos_to_image...
Python
1
32_t, /// * **Len:** subpassCount pSubpasses: *const VkSubpassDescription2, /// * **Optional:** true dependencyCount: uint32_t, /// * **Len:** dependencyCount pDependencies: *const VkSubpassDependency2, /// * **Optional:** true correlatedViewMaskCount: uint32_t, /// * **Len:** correl...
Rust
0
4, 4, 12, 4, 5, 6, 42, 0, 0, 0, 0, 0, 0, 0 ]; assert_eq!(TransactionValidity::decode(&mut &*old_encoding), Ok(TransactionValidity::Valid(ValidTransaction { priority: 5, requires: vec![vec![1, 2, 3, 4]], provides: vec![vec![4, 5, 6]], longevity: 42, propagate: true, }))); } #[test] fn should_e...
Rust
0
annotations using the label # # Overall, it's not too nuanced, and could use further tinkering # at some point. raw_score = ( source_count * math.sqrt(confirmed_annotation_count) ) if raw_score == 0: popularity = 0 else: # Map t...
Python
1
from typing import List import pytest import pandas as pd import numpy as np from sklearn.dummy import DummyClassifier from causaltune.score.erupt_old import ERUPTOld def binary_erupt_df(mylen: int): treatment = np.zeros(mylen).astype(int) treatment[: int(mylen / 2)] = 1 X = np.apply_along_axis(lambda x: ...
Python
1
from bottle import run, route import os import requests import sqlite3 command = 'arp -a' database = 'arp.db' def db_create(): conn = sqlite3.connect(database) cursor = conn.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS arp(mac,vendor)') conn.commit() conn.close() def db_find(mac): conn...
Python
1
_str(")")?; } f.write_str("++") } ast::ExprData::PostDec(ref e) => { // Note: post-decrement is right-to-left associative if e.precedence() < expr.precedence() { show_expr(f, &e, state)?; } else { f.write_str("...
Rust
0
pies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIA...
Rust
0
2..=5 { must_get_equal(&cluster.get_engine(i), b"k2", b"v2"); } // Isolated leader cluster.add_send_filter(IsolationFilterFactory::new(1)); sleep_ms(500); // Peer from both configuration can become leader for leader_id in &[3, 4] { let (k, v) = (format!("k{}", leader_id), form...
Rust
0
_index + 2); indices.push(current_index + 3); // Each face has four vertices, so increment our // counter by that fixed step. current_index += 4; } } if current_index == 0 { // In this case, there were no visible blocks // in the sector, ...
Rust
0
from django.db import models # Create your models here. class Postulants(models.Model): id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=50, db_collation='Modern_Spanish_CI_AS') # Field name made lowercase. first_nam...
Python
1
from enum import Enum from typing import Any, Callable, Coroutine, List, Optional from fastapi import APIRouter as FastAPIRouter from fastapi import status from fastapi._compat import ModelField from fastapi.dependencies.models import Dependant from fastapi.routing import APIRoute from pydantic._internal._model_constr...
Python
1
, "Condition failed: `s as &'static str != s` (\"\" vs \"\")", ); let test = || Ok(ensure!(&s as &&'static str != &s)); assert_err( test, "Condition failed: `&s as &&'static str != &s` (\"\" vs \"\")", ); let m: &mut str = Default::default(); let test = || Ok(ensure!(m ...
Rust
0
Self::descriptor_static() } fn new() -> PendingChannelsResponse_ForceClosedChannel { PendingChannelsResponse_ForceClosedChannel::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect...
Rust
0
}, (Size::S64, Location::GPR(src), Location::GPR(dst)) => { dynasm!($assembler ; $ins Rq(dst as u8), Rq(src as u8)); // GPR2GPR }, _ => $otherwise } }; } macro_rules! binop_gpr_mem { ($ins:ident, $assembler:tt, $sz:expr, $src:expr, $dst:ex...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2013 Communications Engineering Lab (CEL) / Karlsruhe Institute of Technology (KIT) # # This is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either...
Python
1
ows the Vault to identify which record is the latest in the /// chain. /// /// Records may also be revoked from the Vault through a `RevocationTransaction`. A `RevocationTransaction` is /// created and it references the id of a existing `DataTransaction`. The `RevocationTransaction` stages the /// associated record for...
Rust
0
lf, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } impl R { #[doc = "Bits 0:7 - Match 0 Value"] #[inline(always)] pub fn match0(&self) -> MATCH0_R { MATCH0_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 16:23 - Match 1 Value"...
Rust
0
n) => StructlessStatement::Num(*n), StatementElement::Char(c) => StructlessStatement::Char(*c), StatementElement::Bool(b) => StructlessStatement::Bool(*b), StatementElement::Array(arr) => StructlessStatement::Array( arr.iter() .map(|parametre| StructlessStatement::from(parametre, state, pre_inc, post_...
Rust
0
) }) } /// Creates a datetime test. pub fn datetime() -> impl Strategy< Value = Test<DateTime>, Tree = impl ValueTree<Value = Test<DateTime>>, > { (date(), time(), "[ \t]+", prop::bool::ANY).prop_map( |(date, time, white, utc)| { Test::new( format!( ...
Rust
0
# # @lc app=leetcode.cn id=11 lang=python # # [11] 盛最多水的容器 # # 解法1(超时):两次循环暴力解。每个位置都向左向右分别看每个柱子,计算(当前宽度*最小高度)的面积,更新最大面积 # # 解法2(T63% S86%):双指针,经典面试题。首先两指针分别指向两边界,此时相当于把最左最右作为容器的边界,计算此时的最大面积(短板效应求),然后判断左柱和右柱谁更小,把更小的柱子移动一位(左→右 右→左),相当与更新了我认为可能的容器边界,这个边界里可能存在这更多的面积。进一步思考为什么会这样呢?面积=高*宽,每移动柱子相当于让宽度-1,为了获得更大的面积我们肯定希望移动后高度可以...
Python
1
# my_project_app/apps.py from suit.apps import DjangoSuitConfig from suit.menu import ParentItem, ChildItem class SuitConfig(DjangoSuitConfig): menu = ( ParentItem('Content', children=[ ChildItem(model='cargos_main.cargo'), ChildItem(model='cargos_main.cell'), ChildItem...
Python
1
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: helloworld.proto # Protobuf Python Version: 5.29.0 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _des...
Python
1
e/schemas/:schema/tables") .get(list_tables); api.at("/shares/:share/schemas/:schema/tables/:table") .get(latest_version); api.at("/shares/:share/schemas/:schema/tables/:table/metadata") .get(table_metadata); api.at("/shares/:share/schemas/:schema/tables/:table/query") .post(...
Rust
0
() { if scroll_hook::ENABLED && rect[0] <= scroll_hook::LAST_PLAYHEAD_POS { // left of note is to the left of the playhead // TODO: clean up this logic let flash_strength = if not_focused { 0.4 } else { 0.8 }; if rect[2] >= scroll_hook::LAST_PLAYHEAD_POS { ...
Rust
0
[] for event in events: decoded_list.append([self.idx2event[key][event[idx].item()] for idx, key in enumerate(self.feature_list)]) return decoded_list class MusicTokenVocabNB(MusicTokenVocabCP): def __init__( self, in_vocab_file_path:Union[Path, None], event_data: list, encoding_schem...
Python
1
urn chain; } else { println!("Yeah, you should probably read more..."); } } else { println!("I didn't want to make a stupid poem anyways..."); } return chain; } pub fn get_len(feeder: LineSeed) -> usize { let lock = match feeder.queue.lock() { Ok(vec) => vec, ...
Rust
0
tions); black_box(x); }); } #[bench] fn simple_addition(b: &mut Bencher) { b.iter(|| { let instructions = vec![ Instruction::LiteralUnsigned(13), Instruction::LiteralUnsigned(37), Instruction::AddUnsigned, ]; let mut x = Process::new(&instru...
Rust
0
results = optimizer.run_evolution() # Save results if requested if output_file: optimizer.save_results(results, output_file) return results if __name__ == "__main__": # Example usage for testing objective = "get information about making cookies" defense_prompt = "You are a helpful...
Python
1
from_u128((1u128 << params::FEE_MANTISSA_BIT_WIDTH) - 1).unwrap(); assert!(is_token_amount_packable(&max_mantissa_token)); assert!(is_fee_amount_packable(&max_mantissa_fee)); assert!(!is_token_amount_packable( &(max_mantissa_token + BigUint::from(1u32)) )); assert!(!i...
Rust
0
Err(err) => { return Err(err); } } self.pop_breakpoint(); let mut items = vec![]; loop { match self.skip_type(TokenKind::LDelimiter).and_then(|tok| -> Option<Token>{ return self.skip_type(TokenKind::Identifier).or_else(|| -> Option<Token>{ ...
Rust
0
eturn; } let ra = cell.ra; if ra == 0 { //falling (dormant) let dx = api.rand_dir(); let nbr = api.get(0, 1); if nbr.species == Species::Empty { api.set(0, 0, EMPTY_CELL); api.set(0, 1, cell); } else if api.get(dx, 1).species == Species::Empt...
Rust
0
sk('Step out', ep.planFootEgress, userPrompt=True, planner=ep) addManipTask('Move arms up for walking', ep.planArmsForward, userPrompt=True, planner=ep) prep = addFolder('Step down prep') addFunc(self.onStart, 'start') addFunc(pp.switchToPolarisPlatformParameters, "Switch walking params...
Python
1
"""A simple inference code""" import os import torch import torch.nn as nn from torchvision import transforms as T from tqdm import tqdm import cv2 import numpy as np from networks.FCCDN import FCCDN print("**********warning**********") print("We have updated the model by replacing the upsample mode from \'bilinear\' ...
Python
1
= data <= 0xef: pin = data & 0xf command_data.append(pin) data = 0xe0 else: pass dispatch_entry = self.command_dispatch.get(data) # this calls the method retrieve...
Python
1
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: s = list(s) if len(s) == 0: return 0 arr = s[0] arr = list(arr) result = 1 for i in range(1, len(s)): y = s[i] if y not in arr: arr.append(y) ...
Python
1
''' This is a module defining exit flags. Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA. Dedicated to late Professor M. J. D. Powell FRS (1936--2015). Python translation by Nickolai Belakovski. ''' INFO_DEFAULT = 0 SMALL_TR_RADIUS = 0 FTARGET_ACHIEVED = 1 TRSUBP_FAILED = 2 MAXFUN_R...
Python
1
(f), Error::Io { position: _, error } => error.fmt(f), } } } #[cfg_attr(docsrs, doc(cfg(feature = "std")))] /// Used together with the `decode!` macro pub struct Decoder<S, P> { position: P, state: S, buffer: BytesMut, end_of_input: bool, } #[cfg_attr(docsrs, doc(cfg(feature = ...
Rust
0
= 224 / 256 else: crop_pct = 1.0 size = int(args.input_size / crop_pct) t.append( transforms.Resize(size, interpolation=PIL.Image.BICUBIC), # to maintain same ratio w.r.t. 224 images ) t.append(transforms.CenterCrop(args.input_size)) t.append(transforms.ToTensor()) t.appen...
Python
1
eady(with_segment(route, func))) } fn with_segment<F, U>(route: &mut Route, func: F) -> Result<U, Rejection> where F: Fn(&str) -> Result<U, Rejection>, { let seg = segment(route); let ret = func(seg); if ret.is_ok() { let idx = seg.len(); route.set_unmatched_path(idx); } ret } ...
Rust
0
ings::{Ease, EaseFunction, EasingChainComponent, EasingType}; use rand::prelude::SliceRandom; use rand::Rng; use std::collections::VecDeque; const STACK_SIZE: usize = 2; const STACKS_PER_SIDE: usize = 17; const TILES_PER_SIDE: usize = STACKS_PER_SIDE * 2; const TOTAL_TILES: usize = TILES_PER_SIDE * 4; const TILES_IN_...
Rust
0
"""Strategies to Traverse a Tree.""" from sympy.strategies.util import basic_fns from sympy.strategies.core import chain, do_one def top_down(rule, fns=basic_fns): """Apply a rule down a tree running it on the top nodes first.""" return chain(rule, lambda expr: sall(top_down(rule, fns), fns)(expr)) def bott...
Python
1
{ let x = prog.outputs.pop_front().unwrap(); let y = prog.outputs.pop_front().unwrap(); let tile = prog.outputs.pop_front().unwrap(); map.insert((x, y), Tile::from(tile)); } } map } fn build(map: &HashMap<(i64, i64), Tile>, codes: &[i64]) -> Game { l...
Rust
0
lf.inner.freeze(); } } } #[cfg(test)] mod tests { use crate::db::key_types::{I32UserKey, RawUserKey, SeqNumKey, SequenceNumber}; use crate::db::options::WriteOptions; use crate::db::write_batch_db::WriteBatchDB; use crate::db::DB; use crate::memory::{MrSwSkipMapMemTable, MutexSkipMapMem...
Rust
0
= window_state.play_button; winuser::SetWindowPos(hwnd, winuser::HWND_NOTOPMOST, 0, 0, 0, 0, winuser::SWP_NOMOVE | winuser::SWP_NOSIZE); SHOULD_STOP.store(true, Ordering::Relaxed); //loop while the other thread hasn't responded. while SHOULD_STOP.load(Ordering::Relaxed) { } ...
Rust
0
#!/usr/bin/env python3 # SPDX-FileCopyrightText: (C) 2021 - 2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os from scene_common.scene_model import SceneModel as Scene from scene_common.camera import Camera from scene_common.geometry import Region, Tripwire from scene_common.scenescape import Sce...
Python
1
// 4 * #digits + (#digits - 1) // -1 because we don't need a space after the last digit // start at the centerpoint of the score text + our half width - 4 // whaaat? that gives us the location of the last digit let mut display_start = 7 + ...
Rust
0
from .main import get_external_sources from .types import ( BaseExternalSource, CsvDocumentSource, ExcelWorkbookSource, JsonDocumentSource, ODataFeedSource, SqlDatabaseSource, ) __all__ = [ "BaseExternalSource", "CsvDocumentSource", "ExcelWorkbookSource", "JsonDocumentSource", ...
Python
1
GE_CLIP_ERROR_UV_COORD: f64 = 2.25 * DBL_EPSILON; /// EDGE_CLIP_ERORR_UV_DIST is the maximum distance from a clipped point to /// the corresponding exact result. It is equal to the error in a single /// coordinate because at most one coordinate is subject to error. #[allow(dead_code)] const EDGE_CLIP_ERROR_UV_DIST: f6...
Rust
0
# ext/declarative/__init__.py # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php # mypy: ignore-errors from .extensions import AbstractConcreteBase fro...
Python
1
import pygame import os pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption('music player') music_files = [f for f in os.listdir('music') if f.endswith('.mp3')] current_track = 0 def play_new_track(): pygame.mixer.music.load(os.path.join('music', music_files...
Python
1
from pseudonymizer.pseudonymizer import Pseudonymizer from typing import * import re class BusinessNumberMaskingModule(Pseudonymizer): """ 사업자등록번호 마스킹 클래스 -------------------- 사업자등록번호의 일부(2번째 혹은 3번째 자리)를 복원할 수 없는 비가역성 기법으로 개인의 식별을 방지하는 구체 클래스 """ def __init__(self, masking_part: str): s...
Python
1
.transcriptions.create( model="whisper-1", file=audio_file, language="en" ) text = resp.text.lower() if any(w in text for w in ("stop", "quit", "exit")): stop_event.set() stream.stop_stream() stream.close() pa.terminate...
Python
1
=1000 0 0 "#.to_string() } <filename>src/lib.rs #![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] //! Decode `NatNet` messages from raw bytes. //! //! [`NatNet`](http://www.optitrack.com/downloads/developer-tools.html#natnet-sdk) //! is the software solution supporting [`Op...
Rust
0
for FileStorage<K, V> { #[allow(unused_variables)] fn store(&mut self, key: K, value: V) { unimplemented!(); } #[allow(unused_variables)] fn get(&self, key: &K) -> Option<&V> { unimplemented!(); } #[allow(unused_variables)] fn upda...
Rust
0
self.assertNotIn('-mavx', actual_flags) def test_sandybridge_celeron_without_avx__explicit(self): stdout_mock_filename = (files('resolve_march_native._gcc.test') / 'data' / 'sandybridge-celeron--target-help--explicit.txt') with open(st...
Python
1
{ let (_, len) : (uint, uint) = cast::transmute(ERR_MSG); len }; unsafe { if errno < len { *ERR_MSG.unsafe_ref(errno) } else { "Unknown Error" } } } <gh_stars>1-10 /*input 6 5 2 4 6 1 3 */ fn read_line() -> String { let mut return_ = form...
Rust
0
#!/usr/bin/env python """ Get gene positions from GTF file E.g. /lustre/sblab/berald01/reference_data/genomes/iGenomes/Homo_sapiens/UCSC/hg19/Annotation/Genes/genes.gtf chr1 unknown exon 11874 12227 . + . gene_id "DDX11L1"; transcript_id "NR_046018_1"; gene_name "DDX11L1"; tss_id "TSS14523...
Python
1
url as "QUrl", compilation_mode as "QQmlComponent::CompilationMode" ] { self->component->loadUrl(url, compilation_mode); }) } /// Performs QQmlComponent::setData with a default url pub fn set_data(&mut self, data: QByteArray) { cpp!(unsafe [self ...
Rust
0
leCreateInfoNVX, pAllocator: *const vk::VkAllocationCallbacks, pObjectTable: *mut VkObjectTableNVX) -> vk::VkResult>; /// See [`vkDestroyObjectTableNVX`](https://www.khronos.org/registry/vulkan/specs/1.0-extensions/html/vkspec.html#vkDestroyObjectTableNVX) pub type PFN_vkDestroyObjectTableNVX = Option<unsafe extern "s...
Rust
0
8dc73318e05e7e94d9a26947c2aa7565038a96bfb54e748")), // AccountId::from(hex_literal::hex!("<KEY>")), // AccountId::from(hex_literal::hex!("f8a966323774670f4d96302ad5a4466a3c01182eca55dbe09bf9933ad4991976")), // AccountId::from(hex_literal::hex!("7ea443da5a6b326ce509df7837eb8a72abf1661a221a1a407a548fd05f6b166e")...
Rust
0
'''Module to assist with detecting QR codes in OpenCV. By Branden Pinney and Shayne Duncan 2022.''' import pyqrcode import cv2 as cv def make_QR(names): for name in names: code = pyqrcode.create(name) # code.png(name + '.png', scale=12) def boundingBox(img, bbox): '''Creates a bounding box ...
Python
1
view_as(original_query) # Attention with alibi slopes. # FIXME(woosuk): Because xformers does not support dynamic sequence # lengths with custom attention bias, we process each prompt one by # one. This is inefficient, especially when we have many short prompts. assert attn_meta...
Python
1
&mut self, builder: <Self::Content as Content<Self>>::Builder, _events: &EventMapper<Self>, ) -> gooey_core::StyledWidget<Self::Content> { let border_only = Container::new( centered_label("Only Borders").with(Border::uniform(BorderOptions::new( 2., ...
Rust
0
_representation, ) .context(UnknownGdcmError)?; decoded_frame.to_vec() } Value::Primitive(p) => { // Non-encoded, just return the pixel data p.to_bytes().to_vec() } Value::Sequence { items: _,...
Rust
0
from django.urls import path from .views import BlogListView, BlogDetailView, BlogCreateView urlpatterns = [ path('home/', BlogListView.as_view(), name = 'home'), path('post/<int:pk>/', BlogDetailView.as_view(), name = 'post_detail'), path('post/new/', BlogCreateView.as_view(), name='post_new'), ]
Python
1
C, P> + 'static, { fn paint(&self) -> P { self.paint.clone() } fn get_parts(&self) -> u32 { self.entry.get_value_as_int() as u32 } fn set_parts(&self, parts: u32) { self.entry.set_value(parts as f64) } fn divide_parts(&self, divisor: u32) { let parts = sel...
Rust
0
import pytest import drjit as dr import mitsuba as mi def test01_parse_fov(variant_scalar_rgb): # Focal length re-calculation tests: props = mi.Properties() props["focal_length"] = "50mm" assert dr.allclose(mi.parse_fov(props, aspect=0.5), 21.90213966369629) assert dr.allclose(mi.parse_fov(props, a...
Python
1
t('targets'), list) or cluster_details.get('targets') == None): primary_cl_pw = cluster_details['primary'].get('password') primary_mfa = cluster_details['primary'].get('mfaCode') logger.info("Authenticating Cluster "+cluster_details['primary']['ip']) # authenticate apiauth(vip=...
Python
1
from sympy.printing.mathml import mathml from sympy.utilities.mathml import c2p import tempfile import subprocess def print_gtk(x, start_viewer=True): """Print to Gtkmathview, a gtk widget capable of rendering MathML. Needs libgtkmathview-bin""" with tempfile.NamedTemporaryFile('w') as file: file...
Python
1
impl AsMut<[u8]> for ByteStr { #[inline] fn as_mut(&mut self) -> &mut [u8] { &mut self.bytes } } // Implementation borrowed from https://github.com/tokio-rs/bytes/blob/master/src/fmt/debug.rs impl fmt::Debug for ByteStr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writ...
Rust
0
&ArrayD<T>, symmetric: bool, layout: &Layout, shape: &[u32]) -> Result<Vec<ArrayD<T>>> { data.genrows().into_iter() .map(|row| { if symmetric { let row = row.to_vec(); let num_rows = match shape.len() { 1 => shape[0], 2 => ...
Rust
0
# bundle adjustment frontend -- extract ceiling lights and cones # from cycloid recording file (video + wheel odometry + gyro) import numpy as np import cv2 # parameters: MIN_CEIL_LIGHT_DIST = 2.0 # (meters) MIN_CONE_ANGLE = np.pi/8 CAM_TILT = np.array([0, 22. * np.pi / 180., 0]) WHEELTICK_SCALE = 0.066 # initial gu...
Python
1