text
string
label_name
string
labels
int64
&token).await?.data; /// # Ok(()) /// # } /// ``` /// /// You can also get the [`http::Request`] with [`request.create_request(&token, &client_id)`](helix::RequestGet::create_request) /// and parse the [`http::Response`] with [`request.parse_response(&request.get_uri()?)`](helix::RequestGet::parse_response()) pub mod ...
Rust
0
, }; Some(ty) } pub(crate) fn size_of(&self) -> Option<usize> { let size = match self { KNumberTy::Bool | KNumberTy::I8 | KNumberTy::U8 | KNumberTy::C8 => 1, KNumberTy::I16 | KNumberTy::U16 | KNumberTy::C16 => 2, KNumberTy::I32 | KNumberTy::U32 | KNum...
Rust
0
final_ids: model_data = self.all_models_map.get(model_id, {}) #f.write(f"{model_id} {model_data.get('context_length', 0)}\n") context_len = model_data.get('context_length') or DEFAULT_CONTEXT_LENGTH f.write(f"{model_id} {context_len}\n") ...
Python
1
()); assert_eq!(Cow::Borrowed(s), py_string.to_string().unwrap()); } } #[doc = "Reader of register SYNCBUSY"] pub type R = crate::R<u32, super::SYNCBUSY>; #[doc = "Reader of field `SWRST`"] pub type SWRST_R = crate::R<bool, bool>; #[doc = "Reader of field `ENABLE`"] pub type ENABLE_R = crate::R<bool, bool>;...
Rust
0
errors; pub mod generic; use std::fs::File; use std::io::{BufReader, Read}; use std::path::Path; use serde::{Deserialize, Serialize}; pub use errors::HarError; use errors::*; pub use generic::*; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] pub struct Har { pub log: Log, } /// Deserialize a HAR fr...
Rust
0
io::sync::Mutex<MemBlobMultiCore>>, } impl MemBlobMulti { /// Opens the given location for non-exclusive read-write access. pub fn open(config: MemBlobMultiConfig) -> Self { MemBlobMulti { core: config.core } } } #[async_trait] impl BlobMulti for MemBlobMulti { async fn get(&self, _deadline: I...
Rust
0
# # Copyright (c) 2014 ThoughtWorks, Inc. # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pixelated is distrib...
Python
1
"""Event registry for managing handlers and publishers""" from collections.abc import Callable from core.logger import get_module_logger from faststream.redis import RedisRouter logger = get_module_logger(__name__) class EventRegistry: """Registry for managing event handlers across different domains""" d...
Python
1
String>) -> (Vec<Vec<(isize, isize, isize)>>, Vec<Match>) { // Part 1: Read the beacons let mut beacons: Vec<Vec<(isize, isize, isize)>> = Vec::new(); for line in lines.iter() { let lines: Vec<String> = line .split(['\r', '\n'].as_ref()) .filter(|&x| !x.is_empty()) ...
Rust
0
water_level = 50 if water_level > 80: print("Drain water") else: print("Continue")
Python
1
# Copyright 2023 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import json from lxml import etree from odoo import api, models class ResPartner(models.Model): _inherit = "res.partner" @api.model def fields_view_get( self, view_id=None, view_type="f...
Python
1
import pytest from plenum.test.node_request.helper import nodes_last_ordered_equal from stp_core.loop.eventually import eventually from plenum.test.helper import sdk_send_batches_of_random_and_check from plenum.test.malicious_behaviors_node import dont_send_prepare_and_commit_to, reset_sending from plenum.test.check...
Python
1
} ret.append(top_preds) return ret def multi_pose_post_process(dets, c, s, h, w): # dets: batch x max_dets x 40 # return list of 39 in image coord ret = [] for i in range(dets.shape[0]): bbox = transform_preds(dets[i, :, :4].reshape(-1, 2), c[i], s[i], (w, h)) pts = transform_preds(dets[i, :,...
Python
1
seq = 'ACTGATCGATTACGTATAGGAATTCGCTATCATACATATATATATACGATGCGTTCAT' motif = 'GAATTC' motif_loci = seq.find(motif) print(seq[:motif_loci+1]) print(seq[1+motif_loci:])
Python
1
0x76, 0x8d, 0xc9, 0x0b} DEFINE_GUID!{GUID_WICPixelFormat24bppBGR, 0x6fddc324, 0x4e03, 0x4bfe, 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x0c} DEFINE_GUID!{GUID_WICPixelFormat24bppRGB, 0x6fddc324, 0x4e03, 0x4bfe, 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x0d} DEFINE_GUID!{GUID_WICPixelFormat32bppBGR, 0x6fd...
Rust
0
#!/usr/bin/env python3 import argparse from scapy.all import rdpcap, IP, TCP, UDP, Raw, PcapReader import sys from collections import defaultdict def analyze_pcap(pcap_file, target_port=1935): """分析pcap文件的详细信息""" print(f"分析PCAP文件: {pcap_file}") print(f"目标端口: {target_port}") print("=" * 60) try: ...
Python
1
title: Option<&str>) { unsafe { ffi::gtk_window_set_title(self.as_ref().to_glib_none().0, title.to_glib_none().0); } } fn set_titlebar(&self, titlebar: Option<&impl IsA<Widget>>) { unsafe { ffi::gtk_window_set_titlebar( self.as_ref().to_glib_none...
Rust
0
" => return Err(EvaluatorError::Exit), _ => unreachable!(), } return Ok(result); } else { return Err(EvaluatorError::UnknownKeyword(position)); } } ...
Rust
0
oup(1), text) return re.sub(r"\:(\w+)\:`~?(?:_\w+)?\.?(.+?)`", repl, text) def _decorate_cls_with_warning( cls: Type[_T], constructor: Optional[str], wtype: Type[exc.SADeprecationWarning], message: str, version: str, docstring_header: Optional[str] = None, ) -> Type[_T]: doc = cls.__do...
Python
1
16; pub const DAQmx_AI_SoundPressure_dBRef: ::std::os::raw::c_ushort = 10673; pub const DAQmx_AI_Microphone_Sensitivity: ::std::os::raw::c_ushort = 5430; pub const DAQmx_AI_Accel_Units: ::std::os::raw::c_ushort = 1651; pub const DAQmx_AI_Accel_dBRef: ::std::os::raw::c_ushort = 10674; pub const DAQmx_AI_Accel_4WireDCVol...
Rust
0
csv.writer(f) wr.writerows(list_of_lists) ############################################################# # SPLIT HEAD POSE INTO TEST, TRAIN, VAL ############################################################# def split_head_pose(data_dir=LRW_DATA_DIR): # COLLECT NUM OF WORDS IN EACH SET OF EACH WORD ...
Python
1
rs, vec![b, c]); let a_edges = vg.edges(a).map(|eref| eref.target()).collect::<Vec<_>>(); assert_eq!(a_edges, vec![b, c]); let b_edges = vg.edges(b).map(|eref| eref.target()).collect::<Vec<_>>(); assert_eq!(b_edges, vec![c, a]); } #[test] fn test_remove_edge() { le...
Rust
0
pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - EL_ENABLE"] #[inline] pub fn el_enable(&self) -> EL_ENABLER { EL_ENABLER::_from({ const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } ...
Rust
0
class Solution: # Similar to 253. Meeting Rooms II def minGroups(self, intervals: List[List[int]]) -> int: minHeap = [] # Store `right`s for left, right in sorted(intervals): if minHeap and left > minHeap[0]: heapq.heappop(minHeap) heapq.heappush(minHeap, right) return len(minHeap...
Python
1
transaction.try_into_domain(session.user_id(), used_currencies) { Ok(t) => t, Err(error) => return Ok(error.into()), }; let ledger_commands = PostgresCommands(&db); let saved_transaction = match ledger_commands.persist_transaction(transaction).await { Ok(t) => t, Err(error)...
Rust
0
mult(a, b, 4, false) } fn karatsuba_par_wrapper(a: &Bignum, b: &Bignum) -> Bignum { bignum_karatsuba_mult(a, b, 4, true) } #[test] fn bignum_karatsuba_mult_test() { assert_eq!(try_with_strs(karatsuba_wrapper, "2", "2"), "4"); assert_eq!(try_with_strs(karatsuba_wrapper, "-2", "2"), "-4"); assert_eq!(tr...
Rust
0
tsc_frequency as u64 * 1_000_000, ticks_to_mono_numerator: 1000, ticks_to_mono_denominator: tsc_frequency as u32, physmem: PMEM_SIZE as u64, version_string_len: 0, version_string: Default::default(), }; constants.set_version_string(git_version!( prefix = "git-", ...
Rust
0
from functions import get_primes_up_to, get_first_n_primes, get_primes_between def main(): print("Kies een optie:") print("1: Alle priemgetallen tot en met een getal") print("2: De eerste N priemgetallen") print("3: Priemgetallen tussen twee getallen") keuze = input("Voer het nummer van de optie i...
Python
1
add_block(orphan1.clone()), Ok(BlockAddResult::OrphanBlock)); assert_eq!(store.add_block(orphan2), Ok(BlockAddResult::OrphanBlock)); assert_eq!(store.add_block(orphan3), Ok(BlockAddResult::OrphanBlock)); assert_eq!(store.add_block(orphan4.clone()), Ok(BlockAddResult::OrphanBlock)); assert_eq!(store.add_...
Rust
0
ID_LEN])); } let mut remained = inserted.difference(&removed).collect::<HashSet<_>>(); for id in a.iter() { if let IBLTEntry::Inserted(id) = id.unwrap() { assert!(remained.remove(&id.digest)); } } assert!(remained.is_empty()); l...
Rust
0
r::*; fn in_memory_db() -> db::DBLocal { let conn = Connection::open_in_memory().unwrap(); let local_conn = Rc::new(conn); db::initialize_db(local_conn.clone()).unwrap(); local_conn } #[test] fn test_delete_flag() { let conn = in_memory_db(); let mut...
Rust
0
> 0 || succeeded == 0 { process::exit(1); } } trait Environment: Debug { fn start(&mut self) {} fn run(&mut self, bin: &Path, output: Option<&OutputTest>) -> process::Output; fn stop(&mut self) {} } #[derive(Debug)] struct Native; impl Environment for Native { fn run(&mut self, bin: &Path, _output: Option<&Out...
Rust
0
_conv(x_t) # (B, dim, N, 5) x_t = self.init_fc(x_t) # (B, dim, N, dim) t = self.time_mlp(diffusion_step) if exists(self.time_mlp) else None # (B, dim*4) h = [] # downsample counter = 0 for block1, block2, attn, downsample, condition_downsample in self.downs: ...
Python
1
import turtle import figures # Set up the screen window = turtle.Screen() window.bgcolor("lightgreen") # Side length side_length = 50 triangle_lenght = 100 lenght_a = 40 lenght_b = 60 figures.draw_square(side_length) figures.draw_triangle(triangle_lenght) figures.draw_rectangle(lenght_a,lenght_b) # Hide the turtle...
Python
1
let (is_interactive, is_self_play, fen_str, ply_count) = parse(&args).unwrap(); // if run_benchmarks { // run_bench(); // return; // } let board = match Board::from_str(fen_str.as_str()) { Ok(b) => b, Err(_) => { println!("Bad Fen"); return; ...
Rust
0
::Less, (-s_nan()).cmp(&TotalF32(-1.0))); assert_eq!(Ordering::Less, (-s_nan()).cmp(&TotalF32(-0.5))); assert_eq!( Ordering::Less, (-s_nan()).cmp(&TotalF32(-f32::MIN_POSITIVE)) ); assert_eq!(Ordering::Less, (-s_nan()).cmp(&-max_subnorm())); assert_eq!(Orde...
Rust
0
4567962295300549271, 5929583493640677751, 17618207486530478833, 16600462137977359741, 16551719371247820635, 12057922785354578416, 13022559182829558162, 13308285686168533250, 313705269181021, ])), Fq(FqRepr([ 2265581976117350591, ...
Rust
0
from config import model_config, time_range from data import XLSXReader, ExtractData from lib import MetaModel, BaseModel, TimeSplit, DataPipe, TimeGroup from plot import Line from tasks.base_task import BaseTask class ModelTask(BaseTask): task_name = "model" __doc__ = f"""\n{'=' * 4} 模型任务""" group = Tru...
Python
1
_input.len().min(128); input[..len].copy_from_slice(&origin_input[..len]); let sig = match recover_signature(&input) { Some(value) => value, None => { return Err(PrecompileFailure::Error { exit_status: ExitError::Other("Invalid signature".into...
Rust
0
import os import logging from thug.ThugAPI.ThugAPI import ThugAPI log = logging.getLogger("Thug") class TestWebTracking(object): cwd_path = os.path.dirname(os.path.realpath(__file__)) misc_path = os.path.join(cwd_path, os.pardir, "samples/misc") def do_perform_test(self, caplog, url, expected, type_="r...
Python
1
pub difficulty: U256, } // Log is the data struct for LOG0...LOG4. // The members are "Address: Address, Topics: Vec<H256>, Body: Vec<u8>" #[derive(Clone, Debug)] pub struct Log(pub Address, pub Vec<H256>, pub Vec<u8>); #[derive(Clone, Debug)] pub enum InterpreterResult { // Return data, remain gas, logs. Nor...
Rust
0
convolution module. Args: in_channels (int): the number of input channels out_channels (int): the number of out channels kernel_size (int|tuple(int)): kernel size of convolution indice_key (str): the indice key used for sparse tensor stride (int|tuple(int)): the stride of c...
Python
1
| m.as_str()).unwrap_or(""); let mut script = ""; let mut variant = ""; let mut uvariant = ""; match src_variant.as_ref() { // Variants seen in the wild in GNU LibC (via http://lh.2xlibre.net/) or in Debian // GNU/Linux Stretch system. Treatment of...
Rust
0
from functools import reduce import operator def select(cond, aList): return list(filter(cond, aList)) def reject(cond, aList): return select(lambda x: not cond(x), aList) def collect(fun, aList): return list(map(fun, aList)) def anySatisfy(cond, aList): flags = map(lambda x: cond(x), aList) ...
Python
1
_time >= omega_contract.auto_exp_time)?; // allow redemptions at 1 / num_outcomes quantity / (omega_contract.num_outcomes as u64) // no need to check winner mint because token program will fail if it's not a mint controlled by omega } else { check_assert!(*winner_...
Rust
0
# coding: utf-8 # Copyright (C) 1994-2021 Altair Engineering, Inc. # For more information, contact Altair at www.altair.com. # # This file is part of both the OpenPBS software ("OpenPBS") # and the PBS Professional ("PBS Pro") software. # # Open Source License Information: # # OpenPBS is free software. You can redistr...
Python
1
_base_ = 'fcos_r50-caffe_fpn_gn-head_1x_coco.py' # model settings model = dict( data_preprocessor=dict( type='DetDataPreprocessor', mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], bgr_to_rgb=False, pad_size_divisor=32), backbone=dict( dcn=dict(type='DCNv2'...
Python
1
times): now = datetime.now(pytz.UTC) suggestions = [] for time_block in extracted_times: if time_block['type'] == "exact": try: dt = parser.parse(f"{time_block['date']} {time_block['time']}", dayfirst=True) suggestions.append(d...
Python
1
tter) -> fmt::Result { write!(f, "[ERROR] {}", self.description) } } impl Error for ApiError { fn description(&self) -> &str { self.description.as_ref() } } /// Use this method to specify a url and receive incoming updates via an outgoing webhook. /// Whenever there is an update for the bo...
Rust
0
# Draw and move vehicles for vehicle in simulation: self.screen.blit(vehicle.current_image, [vehicle.x, vehicle.y]) vehicle.move() pygame.display.update() except Exception as e: print("\n\n--- E...
Python
1
mut rng); let headers = NonEmpty::from_vec(chain.iter().map(|b| b.header).collect()).unwrap(); let tree = model::Cache::from(headers); let header = tree.get_block_by_height(6).unwrap(); let hash = header.block_hash(); let inv = vec![Inventory::Block(hash)]; let block = ch...
Rust
0
[v]]) output.append(f"Adjacentes de {v.id}: {adjacentes_ids}") return "\n".join(output) def formatar_conversoes(grafo): """Formata a demonstração de conversão entre matriz e lista.""" output = ["\n==== DEMONSTRAÇÃO DE CONVERSÃO ===="] lista_adj_original = grafo.lista_adj m...
Python
1
ntly use this to infer types for completion, hover //! information and various assists. #[allow(unused)] macro_rules! eprintln { ($($tt:tt)*) => { stdx::eprintln!($($tt)*) }; } macro_rules! impl_froms { ($e:ident: $($v:ident $(($($sv:ident),*))?),*) => { $( impl From<$v> for $e { ...
Rust
0
friends=["apple", "banana", "cherry",5,35,45,True,False,"mohiz","ahsan"] print(friends) friends.append("kiwi") # Adding a new item to the list print(friends) l1 = [1, 2, 3] l1.sort() # Sorting the list in ascending order print(l1) l1.reverse() # Reversing the order of the list print(l1) l1.insert(1, 4) # Insert...
Python
1
#!/usr/bin/env python import sys import re import subprocess from jinja2 import Template import replacements TEMPLATENAME = "base.svg.template" # modifiers for layers in order as in keymap MODIFIERS = [ [], ["SHIFT"], ["MOD3"], ["MOD3", "SHIFT"], ["MOD4"], ["MOD4", "...
Python
1
*p let mut elem_nodes = vec![0; num_elem * num_nodes]; for e in 0..num_elem { let mut e_xyz = [1; 3]; let mut re = e; for d in 0..dim { e_xyz[d] = re % num_xyz[d]; re /= num_xyz[d]; } let loc_offset = e * num_nodes; for loc_nodes in 0..num_...
Rust
0
TypeDesc::DateTime => ParamInitMethod::ByValue, TypeDesc::Enum(_) => ParamInitMethod::ByValue, TypeDesc::Array { items } => { let items_type_path = items.type_path(); ParamInitMethod::IntoImpl(parse_quote! { Vec<#items_type_path> }) } ...
Rust
0
ew(0), future_map: DashMap::new(), } } } impl TrackedFutureRegistry { pub fn wrap<F: Future>( registry: Arc<TrackedFutureRegistry>, fut: F, desc: String, ) -> TrackedFuture<F> { TrackedFuture::new(fut, registry, desc) } pub fn register(&self, des...
Rust
0
_mut()); all_widgets.append(&mut self.8.widgets_mut()); all_widgets.append(&mut self.9.widgets_mut()); all_widgets.append(&mut self.10.widgets_mut()); all_widgets.append(&mut self.11.widgets_mut()); all_widgets } } // Copyright 2017 <NAME> // // Licensed under the Apache Lice...
Rust
0
ations, self.config.TASK_CONFIG.TASK.INSTRUCTION_SENSOR_UUID, ) batch = batch_obs(observations, self.device) batch = apply_obs_transforms_batch(batch, obs_transforms) envs_to_pause = [] next_episodes = envs.current_epis...
Python
1
i in 0..(wid * hei) as usize { if !barrier_set.contains(&i) { self.density[i] = rho; self.ux[i] = ux; self.uy[i] = uy; cells[i].c = c; cells[i].e = e; cells[i].n = n; cells[i].w = w; ...
Rust
0
from http import HTTPStatus from fastapi import FastAPI, HTTPException from fast_zero.schemas import Message, UserDB, UserList, UserPublic, UserSchema app = FastAPI() database = [] @app.get('/', status_code=HTTPStatus.OK, response_model=Message) def read_root(): return {'message': 'Olá Mundo!'} @app.post('/...
Python
1
from telebot import TeleBot from confing import TOKEN bot = TeleBot(TOKEN) @bot.message_handler(commands=['rating']) def handle_rating(message): rating_data = [ ('user1', 5), ('user2x', 3), ] rating_data.sort(key=lambda x: x[1], reverse=True) res = [f'| @{x[0]:<11} | {x[1]:<11}|\n{"_"*...
Python
1
x = BatchNormalization(axis=bn_axis, epsilon=2e-5, momentum=0.9, name=name + "_2_bn")(x) x = PReLU(shared_axes=[1, 2], name=name + "_1_prelu")(x) x = ZeroPadding2D(padding=1, name=name + "_2_pad")(x) x = Conv2D( filters, kernel_size, strides=stride, kernel_initializer="...
Python
1
correlated_q, q )); } } } fn get_quantifier_alias(q: &Quantifier) -> String { if let Some(alias) = &q.alias { format!(" as {}", alias) } else { "".to_string() } } fn inc(&mut self) { self.in...
Rust
0
= &ast; let enum_vis = arg_vis.unwrap_or(vis.clone()); let enum_ident = arg_ident.unwrap_or(format_ident!("{}Enum", ident)); let enum_variants: Vec<syn::Ident> = variants.iter().map(|v| v.ident.clone()).collect(); let enum_variants_str: Vec<String> = enum_variants.iter().map(syn::Ident::to_string).coll...
Rust
0
#!/usr/bin/env python import importlib import click from typing import Type from graphorchestrator.toolsetserver.runtime import ToolSetServer def _import_class(dotted: str) -> Type[ToolSetServer]: mod_path, sep, cls_name = dotted.partition(":") if not sep: raise click.ClickException("❌ Specify server ...
Python
1
import numpy as np import math from scipy.optimize import curve_fit import matplotlib.pyplot as plt # Исходные данные x = np.array([1, 2, 3, 4, 5, 6]) y = np.array([2.0, 0.68, 0.44, 0.24, 0.12, 0.14]) # 1. Линейная функция y = a*x + b def linear_func(x, a, b): return a * x + b params_linear, _ = curve_fit(linear...
Python
1
usize, const MAX_WORDS: usize, > where SinsemillaChip: SinsemillaInstructions<C, K, MAX_WORDS> + Clone + Debug + Eq, EccChip: EccInstructions< C, NonIdentityPoint = <SinsemillaChip as SinsemillaInstructions<C, K, MAX_WORDS>>::NonIdentityPoint, FixedPoints = <SinsemillaChi...
Rust
0
mpy.ndarray, filter_value=_MIN_FLOAT ) -> numpy.ndarray: """ Keep top_k logits based on its value. All other values will be overwritten to filter_value :param filter_value: value to overwrite non-top_k values """ logits_shape = logits.shape logits = logits.re...
Python
1
""" Layer/Module Helpers Hacked together by / Copyright 2020 Ross Wightman """ import collections.abc from itertools import repeat # From PyTorch internals def _ntuple(n): def parse(x): if isinstance(x, collections.abc.Iterable) and not isinstance(x, str): return x return tuple(repeat(...
Python
1
#[rustfmt::skip] let a = _mm512_set_pd(f64::NAN, f64::MAX, f64::NAN, f64::MIN, f64::NAN, -1., f64::NAN, 0.); #[rustfmt::skip] let b = _mm512_set_pd(f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::MIN, f64::MAX, -1., 0.); let mask = 0b11000011; let m = _mm512_mask_cmpord_pd_mask(mask...
Rust
0
import re import pytest import pandas._testing as tm from pandas.io.excel import ExcelWriter odf = pytest.importorskip("odf") pytestmark = pytest.mark.parametrize("ext", [".ods"]) def test_write_append_mode_raises(ext): msg = "Append mode is not supported with odf!" with tm.ensure_clean(ext) as f: ...
Python
1
# -*- coding: utf-8 -*- # This code is part of Amoco # Copyright (C) 2017 Axel Tillequin (bdcht3@gmail.com) # published under GPLv2 license from .env import pc from amoco.cas.expressions import top, tst, oper, OP_ASR, OP_LTU, OP_GEU def __npc(i_xxx): def npc(ins, fmap): fmap[pc] = fmap(pc) + ins.length ...
Python
1
cx, cy = 640.0, 360.0 d = math.sqrt(cx * cx + cy * cy) fov = [65.7, 42.3] # Horizontal and vertical FOV fy, fx = intrinsics._calculateFocalLengths(cx, cy, d, fov) expected_fx = cx / math.tan(math.radians(65.7 / 2)) expected_fy = cy / math.tan(math.radians(42.3 / 2)) assert math.isclose(f...
Python
1
'SERVO': try: rospy.wait_for_service('/costar/SetServoMode',2) except rospy.ROSException as e: print 'Could not find SetServoMode service' return try: servo_mode_service = rospy.ServiceProxy('/costar/SetServoMode',SetSer...
Python
1
ator[PeblarData]): """Class to manage fetching Peblar active data.""" def __init__( self, hass: HomeAssistant, entry: PeblarConfigEntry, api: PeblarApi ) -> None: """Initialize the coordinator.""" self.api = api super().__init__( hass, LOGGER, ...
Python
1
.body(body) .send() .await?; match response.status() { StatusCode::BAD_REQUEST => { let content = response.text().await?; Err(InfluxError::InvalidSyntax(content)) } StatusCode::U...
Rust
0
# -*- coding: utf-8 -*- import subprocess import os class AndroidDebugBridge(object): def call_adb(self, command): command_result = '' command_text = 'adb %s' % command # print(command_text) results = os.popen(command_text, "r") while 1: line = results.readline...
Python
1
# run_inference.py from inference import get_completions prompt = "Describe the contents of each image. One sentence per image (if there are more than one)." url_1 = "../images/chess.png" url_2 = "../images/image-1.png" # gqa pic url_3 = "../images/bed.jpg" messages = [ { "role": "user", "content"...
Python
1
import torch.nn as nn import torch class SPP(nn.Module): def __init__(self, M=None): super(SPP, self).__init__() self.pooling_4x4 = nn.AdaptiveAvgPool2d((4, 4)) self.pooling_2x2 = nn.AdaptiveAvgPool2d((2, 2)) self.pooling_1x1 = nn.AdaptiveAvgPool2d((1, 1)) self.M =...
Python
1
ileH5Object['MB-E10-5_chr1']: assert len(targetFileH5Object['MB-E10-5_chr1'][chromosome]) == 3 for gene in targetFileH5Object['MB-E10-5_chr1'][chromosome]: assert len(targetFileH5Object['MB-E10-5_chr1'][chromosome][gene]) == 5 for data in targetFileH5Object['MB-E10-5_chr1'][chr...
Python
1
pub const AddFavorite: Key = Key(ffi::GDK_KEY_AddFavorite as u32); #[doc(alias = "GDK_KEY_Adiaeresis")] pub const Adiaeresis: Key = Key(ffi::GDK_KEY_Adiaeresis as u32); #[doc(alias = "GDK_KEY_Agrave")] pub const Agrave: Key = Key(ffi::GDK_KEY_Agrave as u32); #[doc(alias = "GDK_KEY_Ahook")] pub...
Rust
0
def check_onnxruntime_requirements(minimum_version: Version): """ Check onnxruntime is installed and if the installed version match is recent enough Raises: ImportError: If onnxruntime is not installed or too old version is found """ try: import onnxruntime ort_version = par...
Python
1
import os import psutil import time import sys def start_spider(): os.popen('python spider.py') print('start spider succeed') def start_mongo(): os.popen('mongod --dbpath=F:\data\db') print('start mongod succeed') def kill_spider(pid): os.popen('taskkill /pid {} /f'.format(str(pid))) print(...
Python
1
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np x, y = _me.dynamicsymbols('x y') a, b, r = _sm.symbols('a b r', real=True) eqn = _sm.Matrix([[0]]) eqn[0] = a*x**3+b*y**2-r eqn = eqn.row_insert(eqn.shape[0], _sm.Matrix([[0]])) eqn[eqn.shape[0]-1] = a*_sm.sin(x)**2+b*_sm.co...
Python
1
****************** Your code here ******************************** # Get a reference to your command's inputs. inputs = args.command.commandInputs text_box: adsk.core.TextBoxCommandInput = inputs.itemById('text_box') value_input: adsk.core.ValueCommandInput = inputs.itemById('value_input') # Do so...
Python
1
h pytest.raises(KeyError, match=msg): # missing label directly df.set_index(thing3) with pytest.raises(KeyError, match=msg): # missing label in list df.set_index([thing3]) def test_set_index_custom_label_hashable_iterable(self): # GH#24969 #...
Python
1
import requests with open('massive-body', 'rb') as f: requests.post('http://some.url/streamed', data=f) """Настоятельно рекомендуется открывать файлы в двоичном режиме . Это связано с тем, что Requests может попытаться предоставить Content-Length заголовок для вас, и если это произойдет, это значение будет ус...
Python
1
un(self, sort = True, show_progress_bar = False, contain_original_data = True) -> dict: """Run a complete evaluation. Args: sort (bool): Whether to sort the results by id. show_progress_bar (bool): Whether to display a progress bar. contain_original_data ...
Python
1
return Ok(node.tree().child_heights()); } let mut cloned_node = Tree::decode(node.tree().key().to_vec(), node.tree().encode().as_slice()); let left_child = node.walk(true)?.unwrap(); let left_child_heights = recurse(left_child, remaining_depth - 1, batch...
Rust
0
on for all items currently awaiting cleanup. pub const TRACE_AND_COLLECT_ALL: Self = Self::DEFAULT.set_old_gen_threshold(0); /// Only runs collection for the young generation. This will still move old items to the old /// gen. pub const YOUNG_ONLY: Self = Self::DEFAULT.set_kind(CollectionType::YoungOnly...
Rust
0
_fe), witness: OperationBranchWitness { account_witness: account_witness_before, account_path: audit_path_before, balance_value: Some(balance_before), balance_subtree_path: audit_balance_path_before, }, ...
Rust
0
AR", "world") .build(); let attr: TokenStream = quote! { ("MYVAR") }; let item: TokenStream = quote! { const MYVAR: &'static str = "Hello"; }; let expected: TokenStream = quote! { const MYVAR: &'static str = "world"; }; let result = from_env(attr, item, env); ...
Rust
0
c_path = ['_static'] # This setting is being used by Chef to override a version # stamp inserted # at every page bottom, using a string. For example: chef-client 11.6.x. Or: # Enterprise Chef Server 11.0.x. And yeah, this is just a hack, but it's the # hack that achieved the desired behavior. Plus, there's 0% chance t...
Python
1
""" row, col = 0, 0 for ident, prop in label_map.items(): ind_label = create_label(lo(prop["label"]), weight=QFont.Weight.Bold) val_label = QLabel() val_label.setObjectName(ident + "_label") layout.addWidget(ind_label, row, col) layout.addWidget(val_label, row + 1, col) ...
Python
1
import glob from typing import Iterator, Optional, List from bs4 import BeautifulSoup from dataclasses import dataclass import mistune @dataclass class Adr: title: str status: str body: str index: int = 0 includes_mermaid: bool = False def extract_statuses_from_adr(page_object) -> Iterator[str]...
Python
1
<gh_stars>0 // Copyright 2018 <NAME> // // 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...
Rust
0
on') broadcast_groups = {} broadcast_groups['cn'] = [gid for gid in config.keys() if config[gid]=='国服'] broadcast_groups['jp'] = [gid for gid in config.keys() if config[gid]=='日服'] broadcast_groups['tw'] = [gid for gid in config.keys() if config[gid]=='台服'] return broadcast_groups async def get_ng...
Python
1
from unittest import TestCase from unittest.mock import MagicMock, patch from requests import HTTPError, codes from basketball_reference_web_scraper.client import regular_season_player_box_scores from basketball_reference_web_scraper.errors import InvalidPlayerAndSeason from basketball_reference_web_scraper.http_serv...
Python
1