text
string
label_name
string
labels
int64
be dereferenced when all references to"] #[doc = " the \\ref k4a_capture_t are released with k4a_capture_release()."] #[doc = ""] #[doc = " \\xmlonly"] #[doc = " <requirements>"] #[doc = " <requirement name=\"Header\">k4a.h (include k4a/k4a.h)</requirement>"] #[doc = " <requirement name=\"Li...
Rust
0
GRAVITY = 980 # 重力加速度 ELASTICITY_SCALE = 0 FRICTION_SCALE = 0.8 FRAMES_PER_SECOND = 300 # 1秒間に描画するフレーム数 WAIT_FRAMES = 300 # 観測を送るまでの待機フレーム数 # 30 PYMUNK_FPS = 90 # pymunkの更新頻度 WALL_ELASTICITY = 0.01 * ELASTICITY_SCALE # 壁の弾性係数 WALL_FRICTION = 0.3 * FRICTION_SCALE # 壁の摩擦係数 MAX_FRUIT_NUM = 49 # 最大フルーツ数 GAME_OVER_LI...
Python
1
rrable(&mut self) -> &mut Self { self.options.insert("deferrable".to_string(), OptionValue::Bool(false)); self } fn isolation_level(&mut self, isolation_level: IsolationLevel) -> &mut Self { self.options.insert("isolationLevel".to_string(), OptionValue::String(isolation_level.as_sql().t...
Rust
0
ch.float32) actions = torch.tensor(actions, dtype=torch.float32) states_expert = torch.tensor(states_expert, dtype=torch.float32) actions_expert = torch.tensor(actions_expert, dtype=torch.float32) costs_samp = cost_f(torch.cat((states, actions), dim=-1)) costs_demo = cost_f(torc...
Python
1
from pumpswap_sdk.core.buy_service import buy_pumpswap_token from pumpswap_sdk.core.sell_service import sell_pumpswap_token from pumpswap_sdk.core.pool_service import get_pumpswap_pair_address, get_pumpswap_pool_data from pumpswap_sdk.core.price_service import get_pumpswap_price from pumpswap_sdk.sdk.models import Cons...
Python
1
= BTreeMap<Dn, SubjectAttrs>; #[derive(Serialize, PartialEq, Eq, Debug)] pub struct SubjectsAndCount { pub count: usize, pub subjects: Subjects, } #[derive(Serialize, PartialEq, Eq, Debug)] pub struct SgroupOutAndRight { pub attrs: MonoAttrs, pub sgroup_id: String, pub right: Option<Right>, } ...
Rust
0
#!/usr/bin/env python3 """ Test script to verify fixed Uniswap V3 math functions. """ import sys import os import numpy as np # Add project path sys.path.append(os.path.dirname(os.path.abspath(__file__))) from steerbt.uv3_math import * def test_fixed_functions(): """Test the fixed liquidity calculation function...
Python
1
, &to_triple_where_clauses, rust)?; rust!(rust, "{{"); rust!( rust, "fn to_triple(value: Self) -> Result<({L},{T},{L}), {parse_error}> {{", L = L, T = T, parse_error = parse_error, ); rust!(rust, "match value {{"); rust!...
Rust
0
role_updates.extend( [ self.create_live_update( "mod_1", LiveUpdateType.START, "🛡️ [MODERATOR] Checking content policies..." ), self.create_live_update( "mod_1", ...
Python
1
"""Utilities for vocabularies.""" from typing import Iterable, List from deepr.io.path import Path def write(path: str, vocab: Iterable[str]): """Write vocabulary to file. Parameters ---------- path : str Path to .txt file with one item per line vocab : Iterable[str] Iterable of...
Python
1
match self.reader.read_exact(&mut buf) { Ok(()) => Some(((buf[0] as u16) << 8) + buf[1] as u16), Err(_) => None, } } fn read_u8(&mut self) -> Option<u8> { let mut buf = [0u8; 1]; match self.reader.read_exact(&mut buf) { Ok(()) => Some(buf[0])...
Rust
0
as file: file.write(f"{info}\n") else: txt_fullfn = None script_callbacks.image_saved_callback(params) return fullfn, txt_fullfn IGNORED_INFO_KEYS = { 'jfif', 'jfif_version', 'jfif_unit', 'jfif_density', 'dpi', 'exif', 'loop', 'background', 'timestamp', 'duration', 'progressi...
Python
1
input = [4, 6, 2, 9, 1] def bubble_sort(array): n = len(array) for i in range(n - 1): for j in range(n - i - 1): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] return array bubble_sort(input) print(input) # [1, 2, 4, 6, 9] 가 되어야 합니다! pri...
Python
1
# Copyright lowRISC contributors (OpenTitan project). # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 from typing import Dict, Iterable from serialize.parse_helpers import (check_keys, check_str, check_list, check_int...
Python
1
#!/usr/bin/env python3 # 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. # From here https://www.ranks.nl/stopwords sw = [ 'a', 'about', 'above', 'after', 'again', 'agai...
Python
1
events: i16, revents: i16, } const POLLOUT: i16 = 4; let fds = regs[0] as *mut pollfd; let num_fds = regs[1] as usize; let _timeout = regs[2]; for i in 0..num_fds { let polldat = unsafe { &mut *fds.add(i) }; ...
Rust
0
== 0: strm.write('All passed!\n') else: strm.write('%d files failed lint\n' % nerr) return nerr # singleton helper for lint check _HELPER = LintHelper() def get_header_guard_dmlc(filename): """Get Header Guard Convention for DMLC Projects. For headers in include, direc...
Python
1
job_ids = [] for uri in job["args"]["hosts"]: job_ids.append(HostResource().get_via_uri(uri, bundle.request).id) del job["args"]["hosts"] job["args"]["host_ids"] = json.dumps(job_ids) from chroma_core.services.job_scheduler.job_scheduler...
Python
1
else { let shift: u64 = shift.as_u64(); value >> shift as usize }; ret } pub fn sar(shift: U256, value: U256) -> U256 { let value = I256::from(value); let ret = if value == I256::zero() || shift >= U256::from(256) { let I256(sign, _) = value; match sign { // value is 0 or >=1, pushing 0 Sign::Plus...
Rust
0
:new("usermod") .arg("-aG") .arg("docker") .arg("$USER") .status().await .status_to_unit().unwrap_or(()); Command::new("rm") .arg("-f") .arg("get-docker.sh") .status().await .s...
Rust
0
collect(); let regex_chars = regex.chars().collect(); rematch(&text_chars, &regex_chars, 0, 0, &mut matched); matched } fn rematch(text_chars: &Vec<char>, regex_chars: &Vec<char>, t_idx: usize, r_idx: usize, matched: &mut bool) { // 已经匹配好了,直接...
Rust
0
e { ($($range:ident),*) => {$( impl<T> DynRangeBounds<T> for $range<T> where T: std::cmp::PartialOrd { fn contains(&self, item: &T) -> bool { $range::contains(self, item) } } )*}; } impl_dynrange!(Range, RangeFrom, RangeTo, RangeToInclu...
Rust
0
oy(mut listener: *mut wl_listener, mut data: *mut libc::c_void) { let mut wl: *mut wlr_wl_backend = (listener as *mut libc::c_char).offset(-208) as *mut wlr_wl_backend; backend_destroy(&mut (*wl).backend); } #[no_mangle] pub unsafe extern "C" fn wlr_wl_backend...
Rust
0
_sleep_user_data.is_null() { Box::from_raw(info.wake_sleep_user_data as *mut OWS); }; if !info.advance_user_data.is_null() { Box::from_raw(info.advance_user_data as *mut OA); }; } destroy_simulation_event_cal...
Rust
0
ssMode_WO: _spinAccessMode = 2; pub const _spinAccessMode_RO: _spinAccessMode = 3; pub const _spinAccessMode_RW: _spinAccessMode = 4; pub const _spinAccessMode__UndefinedAccesMode: _spinAccessMode = 5; pub const _spinAccessMode__CycleDetectAccesMode: _spinAccessMode = 6; pub type _spinAccessMode = ::std::os::raw::c_uin...
Rust
0
ue_size(5, v, ::protobuf::wire_format::WireTypeVarint); }; if let Some(v) = self.dynamically_adjust_resolution { my_size += 2; }; if let Some(v) = self.enable_traffic_priority { my_size += 2; }; my_size += ::protobuf::rt::unknown_fields_size(self.g...
Rust
0
equest ) -> aiohttp.web.WebSocketResponse: raise aiohttp.web.HTTPBadRequest(reason="Hello this is a bad request") @routes.get("/websocket_raise_non_http_error", resp_type=ResponseType.WEBSOCKET) async def websocket_raise_non_http_error( self, req: aiohttp.web.Request ) -> aiohttp.web.We...
Python
1
class Producto(): def __init__(self, nombre: str, precio: int, stock:int = 0): self.__nombre = nombre self.__precio = precio self.__stock = stock @property def get_nombre(self): return self.__nombre @property def get_precio(self): return self.__preci...
Python
1
e] pub fn new(own_endpoint: &SocketAddr, k: u16, buckets_capacity: usize) -> Self { //create buckets let mut buckets = Vec::with_capacity(buckets_capacity); for i in 0..buckets_capacity { buckets.push(Bucket::new(k)); } RouteTable { k: k, ...
Rust
0
# # Copyright (C) 2014-2015 UAVCAN Development Team <uavcan.org> # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # This software is distributed under the terms of the MIT License. # # Author: Ben Dyer <ben_dyer@mac.com> # Pavel Kirienko <pavel.kirienko@zubax.com> # import unittest...
Python
1
89,9.21,2.72,9.55l0,0C2.39,10.22,2.87,11,3.62,11h2.44 C6.02,11.33,6,11.66,6,12s0.02,0.67,0.06,1H3.62c-0.38,0-0.73,0.21-0.89,0.55l0,0C2.39,14.22,2.87,15,3.62,15h2.9 c1.24,3.49,4.56,6,8.48,6c1.74,0,3.36-0.49,4.74-1.35c0.69-0.43,0.82-1.39,0.24-1.97l0,0c-0.42-0.42-1.07-0.47-1.57-0.15 C17.42,18.15,16.26,18.5,15,18.5z"/></g>...
Rust
0
ta_y, in_dtype) else: elementwise_ops("4", data_x, data_y, in_dtype, 0) # test for elementwise_floordiv, support int and int64 # paddle1.8 support axis = [0, x_last_dims] # paddle2.x only support axis = -1 floordiv_support_dtype = ['int64', 'int32'] data_x = np.array([-4, 0, -8]) d...
Python
1
# Задача №13. # Уставшие от необычно теплой зимы, жители решили узнать, # действительно ли это самая длинная оттепель за всю историю # наблюдений за погодой. Они обратились к синоптикам, а те, в # свою очередь, занялись исследованиями статистики за # прошлые годы. Их интересует, сколько дней длилась самая # длинн...
Python
1
CK_FLAG_DETECTING_PROXY: u32 = 4096u32; #[doc = "*Required features: 'Win32_Networking_WinHttp'*"] pub const WINHTTP_CALLBACK_FLAG_GETPROXYFORURL_COMPLETE: u32 = 16777216u32; #[doc = "*Required features: 'Win32_Networking_WinHttp'*"] pub const WINHTTP_CALLBACK_FLAG_HEADERS_AVAILABLE: u32 = 131072u32; #[doc = "*Required...
Rust
0
[cfg(unix)] #[test] fn test_login() { let ts = TestScenario::new(util_name!()); for opt in &["-l", "--login", "--log"] { let expected_stdout = unwrap_or_return!(expected_result(&ts, &[opt])).stdout_move_str(); ts.ucmd().arg(opt).succeeds().stdout_is(expected_stdout); } } #[cfg(unix)] #[test...
Rust
0
{ AST::MemberOf(_b(a), _b(b)) } fn _conj(a: AST, b: AST) -> AST { AST::Conjunction(_b(a), _b(b)) } fn _set(vals: Vec<AST>) -> AST { AST::Set(vals) } fn _tup(vals: Vec<AST>) -> AST { AST::Tuple(vals) } fn _bool(val: bool) -> AST { AST::Boolean(val)...
Rust
0
strengths[0] = (uv_f1 * CDEF_SEC_STRENGTHS as i32 + uv_f2) as u8; } pub fn set_quantizers(&mut self, qps: &QuantizerParameters) { self.base_q_idx = qps.ac_qi[0]; let base_q_idx = self.base_q_idx as i32; for pi in 0..3 { self.dc_delta_q[pi] = (qps.dc_qi[pi] as i32 - base_q_idx) as i8; ...
Rust
0
WatchOptions, world: Arc<Mutex<World>>) -> Result<impl warp::Reply, warp::Rejection> { let world = world.lock().unwrap(); let mut result = Vec::with_capacity(PLAYER_GROUP_CAPACITY); let latest_time = match &options.latest { Some(_) => world.world_time, _ => world.get_late...
Rust
0
pub first_event_time: DateTime<Utc>, pub last_event_time: DateTime<Utc>, } #[derive(Clone, Debug, Eq, PartialEq, Hash)] struct CacheKey { pub log_group_name_matcher: LogGroupNameMatcher, pub time_bounds: TimeBounds, pub formatter: format_cwl_log_event::LogFormatter, } #[derive(Clone, Debug)] stru...
Rust
0
ecayRatio: 70.0, Diffusion: 100.0, Density: 100.0, LowShelfFrequency: 250.0, LowShelfGain: 0.0, HighCut: 5650.0, EarlyLateMix: 80.0, WetLevel: -9.8, }; pub const FMOD_PRESET_CAVE: FMOD_REVERB_PROPERTIES = FMOD_REVERB_PROPERTIES { DecayTime: 2900.0, EarlyDelay: 15.0, LateDelay: 22...
Rust
0
let mut html_file = File::open(&path).expect("correct HTML file path"); html_file .read_to_string(&mut html) .expect("read HTML page file"); let document = Document::from(&html); remove_script(&document); remove_style(&document); prep_document(&document); let metadata = get_...
Rust
0
# //CONSTANTS TO USE THRESHOLD = 0.6 WEB_PAGES = 13
Python
1
reteLineTokenAndTargets::ConcreteLineToken(t)), } } fn push_target(&mut self, t: ConcreteLineTokenAndTargets) { match self.breakable_entry_stack.last_mut() { Some(be) => be.push(t.into()), None => self.render_queue.push(t), } } fn push_abstract_token(&mu...
Rust
0
#!/usr/bin/python3 import sys if __name__ == '__main__': if len(sys.argv) < 4: print(f'Usage: {sys.argv[0]} start end code') sys.exit(-1) a = 0 b = 8 start = int(sys.argv[1]) end = int(sys.argv[2]) code = sys.argv[3] N = end - start + 1 step = (b - a)/min(N - 1, 21...
Python
1
""" This module contains functions for correcting ceilometer data """ import numpy as np def correct_ceil(ds, fill_value=1e-7, var_name='backscatter'): """ This procedure corrects ceilometer data by filling all zero and negative values of backscatter with fill_value and then converting the backscatte...
Python
1
print_screen", "mc0"), ("prtr_non", "mc5p"), ("prtr_off", "mc4"), ("prtr_on", "mc5"), ("pulse", "pulse"), ("quick_dial", "qdial"), ("remove_clock", "rmclk"), ("repeat_char", "rep"), ("req_for_input", "rfi"), ("req_mouse_pos", "reqmp"), ("reset_1string", "rs1"), ("reset_2string", "rs2"), ("reset_3string", "r...
Rust
0
# path: f2/apps/weibo/api.py class WeiboAPIEndpoints: """ API Endpoints for Weibo """ # Weibo Domain WEIBO_DOMAIN = "https://weibo.com" # Weibo img domain WEIBO_IMG_DOMAIN = "https://wx4.sinaimg.cn" # 未读好友时间轴 / 全部 UNREAD_FRIENDS_TIMELINE = "/ajax/feed/unreadfriendstimeline" ...
Python
1
Pda; use backtrace::Backtrace; use log; use specs::prelude::*; fn initialize_logger(assets_directory: String) { let yaml_path = format!("{:#}/log4rs.yaml", assets_directory); log4rs::init_file(yaml_path, Default::default()).unwrap(); } fn create_dispatcher<'a, 'b>(raylib_thread: raylib::RaylibThread) -> Dispa...
Rust
0
:join_paths(testing_path.iter().chain(inherited_path.iter()))?; let full_path = full_path.to_str().unwrap().to_owned(); env.insert("PATH".to_string(), full_path); env }; { let (stdout, _stderr) = git.run_with_options( &["smartlog", "--help"], &GitRunOptio...
Rust
0
1, parameter_3, False, False) del parameter_3 # pd_op.add: (-1x5xf32) <- (-1x5xf32, 5xf32) add_3 = paddle._C_ops.add(matmul_2, parameter_2) del matmul_2, parameter_2 # pd_op.matmul: (-1x16xf32) <- (-1x1024xf32, 1024x16xf32) matmul_3 = paddle._C_ops.matmul(relu_1, parame...
Python
1
from fastapi import FastAPI, UploadFile, File from fastapi.responses import JSONResponse from PIL import Image import pytesseract import io app = FastAPI() @app.get("/") async def read_root(): return {"message": "Welcome to the FastAPI OCR Application"} @app.post("/uploadfile/") async def create_upload_file(file...
Python
1
f.models = {} self.model_performance = {} self.current_model = None self.performance_window = deque(maxlen=config.performance_window) logger.info("模型選擇器初始化完成") def register_model(self, model_name: str, model): """ 註冊模型 Args: ...
Python
1
Format, drc_start_up_gain: i8, extra_channel_meaning: Option<ExtraChannelMeaning>, } #[derive(Debug, PartialEq)] struct ExtraChannelMeaning { length: u8, } struct Substream { info: SubstreamInfo, parity: Option<u8>, crc: Option<u8>, } struct SubstreamInfo { restart_nonexistent: bool, ...
Rust
0
_CUTOFF { for (i, elt) in neighbors.iter().enumerate() { if b == *elt { return Ok(i + index); } else if *elt > b { return Err(i + index); } } Err(neighbors.len() + index) } else { ...
Rust
0
on": 2, "result": "updated", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "status": 200, "_seq_no" : 3, "_primary_te...
Rust
0
polling(true); window.set_cursor_pos_polling(true); window.set_cursor_mode(glfw::CursorMode::Normal); window.set_framebuffer_size_polling(true); window.set_refresh_polling(true); window.set_size_limits( 320, 225, glfw::ffi::DONT_CARE as u32, glfw::ffi::DONT_CARE as u32 ); // Center the clie...
Rust
0
{}, num_constraints: {}", a_bits.len(), cs.num_constraints() - x ); // Compare with native results assert_eq!(a_times_gg_vb.get_value().unwrap(), g.mul(&a)); assert_eq!(a_times_gg_fb.get_value().unwrap(), g.mul(&a)); assert!(cs.is_satisfied()); } ...
Rust
0
], vec![ Datum::I64(6), Datum::Bytes(b"b".to_vec()), Datum::Dec(8.into()), Datum::F64(6.0), Datum::F64(6.0), ], vec![ Datum::I64(7), Datum::Bytes(b"f".to_vec()), ...
Rust
0
\"BTC-USD\"")); } #[test] #[serial] #[ignore] // rate limits fn test_get_book() { delay(); let client: Public<Sync> = Public::new(SANDBOX_URL); let book_l1 = client.get_book::<BookRecordL1>("BTC-USD").unwrap(); let str1 = format!("{:?}", book_l1); assert_eq!...
Rust
0
> 0: warnings.warn("%s fileds are useless." % ",".join(memeber_set)) class PayOrderWithBalanceRequest(AbstractModel): """PayOrderWithBalance请求参数结构体 """ def __init__(self): r""" :param _BigDealIdList: 需要支付的大订单号数组 :type BigDealIdList: list of str :para...
Python
1
class Solution: def matrixScore(self, grid: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) def flip(row): row = list(map(lambda x: 1-x, row)) return row def col_sum(y): tot = 0 for a in range(m): tot += grid[a][...
Python
1
rifies that the find_rocket_four_player method correctly identifies the player who has the Rocket 4 card in their hand. """ deck = Deck() rocket4 = Card(Suit.ROCKET, 4) # Create hands with Rocket 4 in a known position hands: List[List[Card]] = [[] for _ in range(4)] ...
Python
1
StdError::NotFound if there is no item with that key /// /// # Arguments /// /// * `storage` - a reference to the storage this item is in /// * `key` - a byte slice representing the key that accesses the stored item pub fn load<T: DeserializeOwned, S: ReadonlyStorage>(storage: &S, key: &[u8]) -> StdResult<T> { Binc...
Rust
0
terface //! //! ### Dispatchable Functions //! //! * `issue` - Issues the total supply of a new fungible asset to the account of the caller of the function. //! * `mint` - Mints the asset to the account in the argument with the requested amount from the caller. Caller must be the creator of the asset. //! * `burn` - Bu...
Rust
0
int; } #[mynewt_macros::safe_wrap(attr)] extern "C" { #[doc = " Sends a start condition and writes <len> bytes of data on the i2c bus."] #[doc = " This API does NOT issue a stop condition unless `last_op` is set to `1`."] #[doc = " You must stop the bus after successful or unsuccessful write attempts."] ...
Rust
0
match env { BuildEnv::Debug => "debug", BuildEnv::Release => "release", }; let workspace_dir = project_context .workspace_dir()? .to_str() .expect("project path") .to_string(); // When workspace_dir is "contracts" we must mo...
Rust
0
oken_rx) = mpsc::sync_channel(1); let state = implicit::State { auth_url: auth_url.to_string(), auth_state_value, token_tx, shutdown_tx: Some(shutdown_tx), }; *implicit::STATE.lock().unwrap() = Some(state); let shutdown_signal = shutdown_rx.map_err(|e| { warn!( ...
Rust
0
normalize_credentials(response.get('Credentials', {})) module.exit_json(changed=changed, sts_creds=credentials) def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( duration_seconds = dict(required=False, default=None, type='int'), mfa_serial_number = ...
Python
1
_t, _bindgen_union_align: u32, } pub type StaticQueue_t = xSTATIC_QUEUE; pub type StaticSemaphore_t = StaticQueue_t; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct xSTATIC_EVENT_GROUP { pub xDummy1: TickType_t, pub xDummy2: StaticList_t, pub ucDummy4: u8, pub muxDummy: portMUX_TYPE, } pub typ...
Rust
0
# Copyright (c) 2021 PaddlePaddle Authors. 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 required by appli...
Python
1
let r = _rchr_c16(aa_ptr, $cc, $start_ptr); if !r.is_none() { return r; } }}; } macro_rules! _unroll_one_rchr_8 { ($a_ptr:expr, $cc:expr, $start_ptr:expr, $loop_size:expr, $idx:expr) => {{ let aa_ptr = unsafe { $a_ptr.add($loop_size * $idx) }; let r = _rchr_c8(aa_ptr...
Rust
0
nstant GpuFillPrimitive { color: [f32; 4] = "color", z_index: f32 = "z_index", local_transform: i32 = "local_transform", view_transform: i32 = "view_transform", width: f32 = "width", } // Per-vertex data. vertex GpuStrokeVertex { position: [f32; 2] = "a_posit...
Rust
0
# Standard Library from unittest.mock import ( MagicMock, patch, ) # wger from wger.core.tests.base_testcase import WgerTestCase from wger.exercises.cache import ( cache_api_exercises, cache_exercise, ) from wger.exercises.models import Exercise class TestCacheExercise(WgerTestCase): @patch('wger...
Python
1
# pylint: disable=missing-docstring, missing-return-doc, missing-param-doc, disallowed-name import re import sqlalchemy from dbally.iql import IQLFiltersQuery from dbally.iql._query import IQLAggregationQuery from dbally.views.decorators import view_aggregation, view_filter from dbally.views.sqlalchemy_base import S...
Python
1
# Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt # import frappe from frappe.model.document import Document class DesignationSkill(Document): pass
Python
1
import cv2 import numpy as np import matplotlib.pyplot as plt def remove_holes(my_image): my_image = cv2.threshold(my_image, 128, 255, cv2.THRESH_BINARY)[1] C = np.logical_not(my_image).astype(np.uint8) # Find connected components num_labels, labels, stats, centroids = cv2.connectedCompo...
Python
1
ring(), grpc_api_address: "127.0.0.1:9191".to_string(), grpc_tls_server_cert: "".to_string(), grpc_tls_server_key: "".to_string(), raft_config: Default::default(), } } } impl Config { /// As requires by [RFC: Config Backward Compatibility](https://github....
Rust
0
# -*- coding: utf-8 -*- # @Time : 2023/10/23 10:23 # @Author : chenlelan # @File : CreateFeaturesHandeler.py import os.path import glob from FlowDivider import FlowDivider from Windows import Windows from FeaturesExt_1 import FeaturesExt from SavetoCsv import CSV import pickle class CreateFeaturesHandeler(): ...
Python
1
kGravity = 3; pub const GDK_GRAVITY_WEST: GdkGravity = 4; pub const GDK_GRAVITY_CENTER: GdkGravity = 5; pub const GDK_GRAVITY_EAST: GdkGravity = 6; pub const GDK_GRAVITY_SOUTH_WEST: GdkGravity = 7; pub const GDK_GRAVITY_SOUTH: GdkGravity = 8; pub const GDK_GRAVITY_SOUTH_EAST: GdkGravity = 9; pub const GDK_GRAVITY_STATI...
Rust
0
e period to monitor. rN)_period_break_maskr*nonzero)rrmaskr-r-r. _period_breaks rnpt.NDArray[np.bool_]cCs&t||}t|d|j|}||kS)Nr)getattrr)rrcurrentrFr-r-r.rs r label_flagsrbool...
Python
1
""" URL configuration for core project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/5.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') ...
Python
1
ics_algos[idx_s, idx_m, idx_a] = metric_score["value"] if masked: mask = get_mask_invalid(scores_scenes_metrics_algos) scores_scenes_metrics_algos = np.ma.masked_array(scores_scenes_metrics_algos, mask=mask) return scores_scenes_metrics_algos # project file handling: algorithms def get_ava...
Python
1
type Error = Error; fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> where K: serde::de::DeserializeSeed<'de>, { if self.len > 0 { self.len -= 1; let key = try!(serde::de::Deserial...
Rust
0
\xd1\xd5(\xbaI{\ ]E\xc3\xf9O\x17\x1a\xff\x00c\x1a\x0ce\xa9S\xb8\ \xd9\x14\xeaC\xd2\xe3\xb2\xa7oV\xb6}J\x9aro\ \xd8\x8e\x1c\xa9\xa7R\x9a\xf0R\xe2\xceR\xc7/\x22T\ \xb4\xbayx\x95L>\x9d=\x1fo\x98\x1b/\xdd\x09\ \xda\xc5.\xd2\xf5\x9b\x0b}\x1e\xdav\xfaF\x9a\xe7\xdc\ N\xb6\x15J\xb3\x9637\xf2W\xa2\xb0\xbew\xd7\x0b\ \x18\xdbZ\xe...
Python
1
from .FTXMain import FTXMain from jesse.enums import exchanges class FTXUSSpot(FTXMain): def __init__(self) -> None: # import here instead of the top of the file to prevent the possible circular imports issue from jesse.modes.import_candles_mode.drivers.FTX.FTXSpot import FTXSpot super()....
Python
1
tCodec; #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] pub enum ConnectionType { /// Sender hasn't tried to connect to peer. NotConnected = 0, /// Sender is currently connected to peer. Connected = 1, /// Sender was recently connected to peer. CanConnect = 2, /// Sender tried to connect...
Rust
0
gs = parser.parse_args() app_name = args.app_name dist_dir = Path(sys.argv[0]).parent.joinpath(args.dist_dir).resolve() if not prepare_resources(): sys.exit(-1) if not init_global_vars(dist_dir, app_name, args): sys.exit(-1) update_license_file(app_name) if not gen_pre_vars(...
Python
1
, labels: labels!(), }, &SummaryMetric { quantiles: vec![ SummaryQuantile { quantile: 0.01, value: 3102.0 }, SummaryQuantile { quantile: 0.05, value: 3272.0 }, SummaryQuantile ...
Rust
0
# quote_features/nbbo_ineligible_share.py from __future__ import annotations import datetime as dt from pathlib import Path from collections import defaultdict from typing import Dict, Iterable, Set import numpy as np import pandas as pd import pyarrow.parquet as pq from feature_base import FeatureContext from quote_...
Python
1
: OriginFor<T>, #[pallet::compact] class: T::ClassId, #[pallet::compact] instance: T::InstanceId, ) -> DispatchResult { let origin = ensure_signed(origin)?; let details = Asset::<T, I>::try_get(&class, &instance).map_err(|_| Error::<T, I>::NotFound)?; let dest = details.ready_transfer.as_ref().ok_o...
Rust
0
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
Python
1
ifiers ISRC, Barcode, CatalogNumber, Movement, MovementIndex, // Flags FlagCompilation, FlagPodcast, // File Information FileType, FileOwner, TaggingTime, Length, OriginalFileName, OriginalMediaType, // Encoder information EncodedBy, EncoderSoftware, EncoderSettings, EncodingT...
Rust
0
return unescape_string_inner(&bytes[0..index], &bytes[index..]).map(Cow::Owned); } } Ok(Cow::Borrowed(value)) } fn unescape_string_inner(start: &[u8], rest: &[u8]) -> Result<String, Error> { let mut unescaped = Vec::with_capacity(start.len() + rest.len()); unescaped.extend(start); ...
Rust
0
failures.append((proxy, evalres)) else: failures.append(Exception(msg.error)) aggregated_result = context.strategy.aggregate_evaluate( current_round, results, failures ) loss_aggregated, metrics_aggregated = aggregated_result # Write history if loss_aggregated is ...
Python
1
def how_many_times(string: str, substring: str) -> int: """ Find how many times a given substring can be found in the original string. Count overlaping cases. >>> how_many_times('', 'a') 0 >>> how_many_times('aaa', 'a') 3 >>> how_many_times('aaaa', 'aa') 3 """ if string == substring:...
Python
1
avg_latency.get_metric_with_label_values(&[client_id]) { metric.set(latency_stats.avg as i64); } if let Ok(metric) = bytes_sent.get_metric_with_label_values(&[client_id]) { metric.set(req_size_stats.sum as i64); } } #[tokio::main] async fn main() -> Result<(), RedisError> { // or use a counter here if ...
Rust
0
ha1)); /// /// # fn main() { /// assert_eq!(parser("-abc"), Ok(("", "abc"))); /// assert_eq!(parser("abc"), Err(Err::Error(("abc", ErrorKind::Char)))); /// assert_eq!(parser("-123"), Err(Err::Error(("123", ErrorKind::Alpha)))); /// # } /// ``` #[macro_export(local_inner_macros)] macro_rules! preceded( ($i:expr, $subm...
Rust
0
global g_config_cloud # 尝试读取远程配置 try: raw_config = toml.load(path.join(save_dir, cloud_config_filename)) g_config_cloud.auto_update_config(raw_config) except Exception as e: logger.debug("读取远程配置失败", exc_info=e) try_update_config_cloud() # 标记为已经初始化完毕 g_config_cloud.lo...
Python
1
); let color = color .map(|c| ((c as f64 / self.population as f64).round() as u8)) .into_image_rgb(); dbg!(color); Color { color, population: self.population as usize, } } fn volume(&self) -> usize { self.bounds.volume() ...
Rust
0
{:.3f}, Acc@5 {:.3f}'.format(test_acc, test_acc_top5)) logger.log_value('test_acc', test_acc, epoch) logger.log_value('test_acc_top5', test_acc_top5, epoch) logger.log_value('test_loss', test_loss, epoch) # save the best model if test_acc > best...
Python
1