text
string
label_name
string
labels
int64
thon js["date"], js["hours"], js["minutes"], js["seconds"], js["milliseconds"] * 1000, dt.timezone.utc, ) datetime_serialization = {"from_json": datetime_from_json, "to_json": datetime_to_json} class Instanc...
Python
1
.write_resource::<ServerResource<G>>(); let recv_rx = server_resource .recv_rx .lock() .expect("Couldn't get lock on wire message receiver") .take() .expect("Somebody already took it!"); RecvSystem { log: parent_log.new(o!()), ...
Rust
0
if occ_nbrs == 0 { t[i][j] = b'#'; } } b'#' => { if occ_nbrs >= 5 { t[i][j] = b'L'; } } _ => {...
Rust
0
import numpy as np import matplotlib.pyplot as plt def enhanced_genetic_algorithm(G=100, PopSize=50, Dv=1, n=14, Pm=0.2, TournSize=2, OffsProb=0.5, LowLim=-100, UppLim=100): # Objective Function def objective_function(x): return -(0.001 * x**2) + 3.7 + np.cos(x / 4 + np.pi / 6) # Generate initial ...
Python
1
_owned(); } if !new_line.is_empty() || empty_lines { output.push_str("\r\n"); output.push_str(&new_line); } } output } fn diff_linemode_nway(base_text: &str, modified_text: &[String]) -> (HashMap<char,String>,Vec<Vec<Diff>>,String) { let mut all_strings = m...
Rust
0
onfig.verify_llvm_ir { let pass = llvm::LLVMRustFindAndCreatePass("verify\0".as_ptr().cast()); llvm::LLVMRustAddPass(pm, pass.unwrap()); } // When optimizing for LTO we don't actually pass in `-O0`, but we force // it to always happen at least with `-O1`. // ...
Rust
0
""" SortinoHyperOptLossDaily This module defines the alternative HyperOptLoss class which can be used for Hyperoptimization. """ import math from datetime import datetime from pandas import DataFrame, date_range from freqtrade.optimize.hyperopt import IHyperOptLoss class SortinoHyperOptLossDaily(IHyperOptLoss): ...
Python
1
o("开始执行分子活性预测机器学习项目") # 1. 数据加载和预处理 print("\n🔄 1. 数据加载和预处理...") logging.info("开始数据加载和预处理") data_loader = DataLoader() df = data_loader.load_and_preprocess() # 2. 准备模型数据 print("\n🔄 2. 准备模型数据...") logging.info("准备模型数据") ...
Python
1
`Poll`]: super::task::Poll //! [`poll_next`]: AsyncIterator::poll_next //! //! # Implementing Async Iterator //! //! Creating an async iterator of your own involves two steps: creating a `struct` to //! hold the async iterator's state, and then implementing [`AsyncIterator`] for that //! `struct`. //! //! Let's make an...
Rust
0
Matrix) -> bool { let dend_prim = primitive( &mut mat.matrix(), mat.len(), Method::Single); let dend_nnchain = nnchain( &mut mat.matrix(), mat.len(), MethodChain::Single); dend_prim == dend_nnchain } fn prop_nnchain_complete_primitive(...
Rust
0
else: print("angle_4 set error!") elif s_id == 5: if 0 <= s_angle <= 270: value = self.__arm_convert_value(s_id, s_angle) self.set_uart_servo(s_id, value, run_time) else: print("ang...
Python
1
u64, _INTR_CLEAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_CLEAR; #[doc = "`read()` method returns [intr_clear::R](intr_clear::R) reader structure"] impl crate::Readable for INTR_CLEAR {} #[doc = "`write(|w| ..)` method takes [intr_clear::W](intr_clear::W) writer structure"] impl crate::Writable for INTR...
Rust
0
st GIGABIT: u128 = 125_000_000; /// GB pub const GIGABYTE: u128 = 1_000_000_000; /// GiB pub const GIBIBYTE: u128 = 1 << 30; /// Tb pub const TERABIT: u128 = 125_000_000_000; /// TB pub const TERABYTE: u128 = 1_000_000_000_000; /// TiB pub const TEBIBYTE: u128 = 1 << 40; /// Pb pub const PETABIT: u128 = 125_000_000_000...
Rust
0
, given name, date of birth and sex into sequence //! `XXXZZDDMMYYYYN`. //! Where `XXX` encodes family name, `ZZ` encodes given name, `DDMMYYYY` encodes date of birth and //! `N` encodes sex. extern crate chrono; use chrono::NaiveDate; use chrono::format::ParseResult; use std::error::Error; use std::fmt; use self::S...
Rust
0
""" AmyAlmond Project - core/utils/user_management.py Open Source Repository: https://github.com/shuakami/amyalmond_bot Developer: Shuakami <3 LuoXiaoHei Copyright (c) 2024 Amyalmond_bot. All rights reserved. Version: 1.2.0 (Pre_827001) user_management.py - 用户管理模块,负责用户名映射的加载和保存 """ import json from config import US...
Python
1
new().expect("executor should build"); let builder = SourceTaskBuilder::new(sources::AudioSourceType::BigBen); let inspector = inspect::component::inspector(); let root = inspector.root(); let d = DataStreamInspect::default().with_inspect(root, "stream").expect("attach to tree"); // Minimum SBC re...
Rust
0
wDesc: cudnnFilterDescriptor_t, w: *const ::std::os::raw::c_void, dyDesc: cudnnTensorDescriptor_t, dy: *const ::std::os::raw::c_void, convDesc: cudnnConvolutionDescriptor_t, algo: cudnnConvolutionBwdDataAlgo_t, workSpace: *mut ::std::os::raw::c_void, workSpaceSiz...
Rust
0
from lc import * # https://leetcode.com/problems/find-champion-ii/discuss/4252315/Python-in-degree-state-2-lines class Solution: def findChampion(self, n: int, edges: List[List[int]]) -> int: roots = [i for i in range(n) if i not in set(map(lambda x: x[1], edges))] return roots[0] if len(roots) ==...
Python
1
8(&byte_vec).unwrap(); prop_assert_eq!(native(binary, encoding), Ok(Atom::str_to_term(s))); Ok(()) }, ); } <reponame>iCalculated/RandomImage #[macro_use] extern crate criterion; extern crate rand; use criterion::Criterion; use rand::Rng; use rand::distributions::{Distribution, Un...
Rust
0
1), Some(c2)) if c1 == c2 => continue, (Some(_), Some(_)) => return false, } } } } impl Eq for Version {} impl PartialOrd for Version { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for Version { fn cmp(&self, ...
Rust
0
from mmengine.config import read_base from seg.models.decode_heads.dsnet_head import DSNetHeadV2 with read_base(): from .unet_segnext_b_160k_synapse import * # noqa model.update(dict( decode_head=dict( type=DSNetHeadV2, ratio=16))) vis_backends = [ dict(type=LocalVisBackend), dict( ...
Python
1
import json import pandas as pd import numpy as np def load_json(jsonpath): """ Loads in data from a json file. Inputs: the filepath for the json file """ with open(jsonpath, 'r') as file: data = json.load(file) return data def extract_all_shapes(json_path): """ Converts a json...
Python
1
nwrap_or("Silence!"); Ok(world_str.into()) } fn main() { let _ = env_logger::init(); let addr = "127.0.0.1:8091".parse().unwrap(); let mut r = Router::new(); r.get("/:hello/:world", params); r.get("/say/*text", say); let s = Server::new(addr, r); s.start_http(); }<gh_stars>1-10 /* * T...
Rust
0
import scrapy class IndeedSpider(scrapy.Spider): name = 'vagasbot' def start_requests(self): urls = [ 'https://br.indeed.com/jobs?q=Python&l=&from=searchOnHP&vjk=6bd88114d2731350'] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self...
Python
1
{ let res = match self { Exp::Bool(b) => format!("{}", b), Exp::Symbol(s) => format!("'{}", s), Exp::Number(n) => format!("{}", n), Exp::List(l) => format!("{:?}", l), Exp::Closure(_) => "<Closure>".into(), Exp::Primitive(_) => "<Primitive...
Rust
0
import streamlit as st print("Salut, c'est Faoussane,🤓") nom_esperé = "nina" date_naissance_esperee = "2004" st.title("Message d'anniversaire") nom = st.text_input("Entrez votre nom :").strip().lower() if nom == nom_esperé: date_naissance = st.text_input("Entrez votre date de naissance (Année seulement) :").str...
Python
1
import numpy as np # Parameters ntype = 60 minsigma = 0.4 maxsigma = 1.6 # Compute size array binsize = (maxsigma - minsigma) / ntype sizes = np.array([minsigma + (i + 0.5) * binsize for i in range(ntype)]) # WCA cutoff factor cut_factor = 2 ** (1 / 6) # Prepare output lines for LJ/WCA pair_lines = [] for i in ran...
Python
1
other) } /// 'Greater than or equal to' comparison for two `StrongArc`s. /// /// The two are compared by calling `>=` on their inner values. /// /// # Examples /// /// ``` /// use std::sync::Arc; /// /// let five = StrongArc::new(5); /// /// assert!(five >= StrongArc::ne...
Rust
0
tower, wait_for_last_vote_in_tower_to_land_in_ledger, RUST_LOG_FILTER, }, log::*, serial_test::serial, solana_core::validator::ValidatorConfig, solana_ledger::{ ancestor_iterator::AncestorIterator, blockstore::Blockstore, blockstore_db::{AccessType, BlockstoreOptions}...
Rust
0
'a mut W { self.variant(VALCTRL_A::VALCTRL_0) } #[doc = "Outgoing Validity always clear"] #[inline(always)] pub fn val_ctrl_1(self) -> &'a mut W { self.variant(VALCTRL_A::VALCTRL_1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { ...
Rust
0
pub fn module_api(&self) -> &::apis::ModuleApi { self.module_api.as_ref() } pub fn system_information_api(&self) -> &::apis::SystemInformationApi { self.system_information_api.as_ref() } } <reponame>tcr/parser-c<filename>src/syntax/ops.rs<gh_stars>10-100 // Original file: "Ops.hs" // ...
Rust
0
, y_center: a }, CirclePosition { x_center: b, y_center: a/2 }, CirclePosition { x_center: 2*b, y_center: 0 }, CirclePosition { x_center: 2*b, y_center: -a }, CirclePositio...
Rust
0
weenRep(msg)), Err(err) => Err(err) } } else if msg_type == 79 { let res: Result<DestroyTableReq, DecodeError> = Message::decode(msg_bytes); match res { Ok(msg) => Ok(BoxedMsg::DestroyTableReq(msg)), Err(err) => Err(err) } } else if msg_type ==...
Rust
0
// Initial setup: everything should work. { let conn = rusqlite::Connection::open(&sql_path)?; let _store = SqliteStore::from_conn(conn, &tmp_dir)?; } // Second setup: shouldn't need to upgrade. { let conn = rusqlite::Connection::open(&sql_path)?;...
Rust
0
test!( min_conains_special_fn_calc_with_div_and_spaces, "a {\n color: min(calc(1 / 2));\n}\n", "a {\n color: min(calc(1 / 2));\n}\n" ); test!( min_conains_special_fn_calc_with_div_without_spaces, "a {\n color: min(calc(1/2));\n}\n", "a {\n color: min(calc(1/2));\n}\n" ); test!( min_cona...
Rust
0
continue if card.valid: valid += 1 cards += [card] elif card.parsed: invalid += 1 if verbose: print 'Invalid card: ' + json_cardname else: unparsed += 1 ...
Python
1
` to return the weight used in `on_finalize`. fn on_initialize(_: T::BlockNumber) -> Weight { <T as Config>::WeightInfo::on_finalize() } fn on_finalize(_: T::BlockNumber) { NextFeeMultiplier::<T>::mutate(|fm| { *fm = T::FeeMultiplierUpdate::convert(*fm); }); } #[cfg(feature = "std")] fn integ...
Rust
0
(f"Received message from client: {client_msg}") response = { "status": "success", "echo": infer(client_msg["message"]), } processTTS(character="lindaiyu", text=response["echo"]) await websocke...
Python
1
5801238806493, -0.6292984099593792]) path.append([0.7058209224773704, 0.9949196900829661, -1.2707519285933635, 1.8416331311726664, -0.9232453238841121, -0.6590722605962089]) # execute Path execute_trajectory(PR2, joint_idx, path, sleep=0.1) print("=======================================") """ Exam...
Python
1
) ); } impl Default for FunctionParameter { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Debug, Hash, PartialEq, Eq)] pub struct AlterFunctionStmt { pub type_: NodeTag, pub objtype: ObjectType, pub func: *mut ObjectWithArgs, #[doc = " name and args o...
Rust
0
he fastx reader /* std use */ /* crate use */ use bstr::io::BufReadExt; use bstr::ByteSlice; /* project use */ use crate::error::Error; use crate::record::Record; use crate::records::Records; /// Struct to perform reade of fasta or fastq file pub struct Reader<R> where R: std::io::BufRead, { inner: bstr::io...
Rust
0
std::mem; use super::LinkList; fn delete_duplicates(mut link: LinkList) -> LinkList { let mut unique_data = HashSet::new(); let mut node = &mut link.head; while node.is_some() { if unique_data.contains(&node.as_ref().unwrap().data) { let temp = node.take(); mem::swap(node,...
Rust
0
result = response.json () # print(result) level = result['level'] # 当前等级 complete_level = result['complete_level'] # 完成等级 msg ("【账号{0}】【plant_id:{3}】成功浇水10g,当前等级{1},种子成熟等级为{2}".format (account, level, complete_level, plant_id)) time.sleep (5) ...
Python
1
assert_eq!(price(&[180, 154, 2], &mut 0), 18100); assert_eq!(price(&[228, 6], &mut 0), -420); assert_eq!(price(&[156, 3], &mut 0), 220); assert_eq!(price(&[194, 7], &mut 0), -450); assert_eq!(vol_amount(1235775464), 1379837.0); assert_eq!(vol_amount(1326643033), 2465683712.0); // let arr = [235...
Rust
0
y_action[link] except KeyError: raise ValueError("invalid value '%s' for 'link' argument" % link) if verbose >= 1: if os.path.basename(dst) == os.path.basename(src): log.info("%s %s -> %s", action, src, dir) else: log.info("%s %s -> %s", action, src, dst) if...
Python
1
} #[inline] pub fn allocate_lig_id(&mut self) -> u8 { let mut lig_id = self.next_serial() & 0x07; if lig_id == 0 { // In case of overflow. lig_id = self.next_serial() & 0x07; } lig_id as u8 } } // TODO: to iter if possible macro_rules! foreach_clust...
Rust
0
_features['target_type'][fi] negative_feature = tt == TargetType.NO_ANSWER if negative_feature: assert not example_has_answer def test_eval_preprocessing_runs_without_errors(self, eval_examples, preprocessor): eval_examples, eval_features = preprocessor.process_eval(...
Python
1
pub fn adcsref_1(self) -> &'a mut W { self.variant(ADCSREFW::ADCSREF_1) } #[doc = "ADC Select Reference 2"] #[inline] pub fn adcsref_2(self) -> &'a mut W { self.variant(ADCSREFW::ADCSREF_2) } #[doc = "ADC Select Reference 3"] #[inline] pub fn adcsref_3(self) -> &'a mu...
Rust
0
Key, KeyEvent}, }; // --- KEYS -- pub static ELEMENT_TEXT_BOX: &'static str = "text_box"; static ID_CURSOR: &'static str = "id_cursor"; // --- KEYS -- #[derive(Clone)] enum TextBoxAction { Key(KeyEvent), Mouse(Mouse), } /// The `TextBoxState` handles the text processing of the `TextBox` widget. #[derive(D...
Rust
0
} } /// This task measures the time difference between two received responses fn graphics_measuring_task(_arg_val: usize) -> Result<(), &'static str>{ let hpet = get_hpet().ok_or("couldn't get HPET timer")?; let mut vec = Vec::with_capacity(200); let mut start_hpet: u64; let mut end_hpet: u64; ...
Rust
0
# -*- coding: utf-8 -*- # Copyright 2025 Google LLC # # 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...
Python
1
# -*- coding: utf-8 -*- """ Created on Sat Jun 21 10:22:57 2025 @author: jwang """ def reverseOnlyLetters(s): """ :type s: str :rtype: str """ letter_reversal = [] for i in range(len(s)): if s[i].isalpha() == True: #if the character is a letter letter_reversal.append(' ') ...
Python
1
# AI-generated module (ChatGPT) import re from typing import Dict, Optional def load_dotenv(dotenv_str: str, environ: Optional[Dict[str, str]] = None) -> Dict[str, str]: """ Parse a DOTENV-format string and return a dictionary of key-value pairs. Handles quoted values, comments, export keyword, and blank ...
Python
1
pub use self::text_area::TextArea; pub use self::text_view::{TextContent, TextContentRef, TextView}; pub use self::tracked_view::TrackedView; /// Same as [`LastSizeView`](self::LastSizeView). #[deprecated(note = "`SizedView` is being renamed to `LastSizeView`")] pub type SizedView<T> = LastSizeView<T>; /// Same as [`...
Rust
0
it__(self): r""" :param _DedicatedClusterSet: 符合查询条件的专用集群列表 :type DedicatedClusterSet: list of DedicatedCluster :param _TotalCount: 符合条件的专用集群数量。 :type TotalCount: int :param _RequestId: 唯一请求 ID,由服务端生成,每次请求都会返回(若请求因其他原因未能抵达服务端,则该次请求不会获得 RequestId)。定位问题时需要提供该次请求的 RequestId。...
Python
1
mm_k1z_xmmm64, /// `VPBROADCASTQ xmm1 {k1}{z}, xmm2/m64` /// /// `EVEX.128.66.0F38.W1 59 /r` /// /// `AVX512VL and AVX512F` /// /// `16/32/64-bit` EVEX_Vpbroadcastq_xmm_k1z_xmmm64, /// `VPBROADCASTQ ymm1 {k1}{z}, xmm2/m64` /// /// `EVEX.256.66.0F38.W1 59 /r` /// /// `AVX512VL and AVX512F` /// /// `16/32/...
Rust
0
.move_on_after(0.950): await trio.serve_listeners(None, [listener]) # type: ignore[arg-type] assert len(caplog.records) == 10 for record in caplog.records: assert "retrying" in record.msg assert record.exc_info is not None assert isinstance(record.exc_info[1], OSError) ...
Python
1
_PADCHAR = "=" _ALPHA = "LVoJPiCN2R8G90yg+hmFHuacZ1OWMnrsSTXkYpUq/3dlbfKwv6xztjI7DeBE45QA" def _getbyte(s, i): x = ord(s[i]) if x > 255: print("INVALID_CHARACTER_ERR: DOM Exception 5") exit(0) return x def get_base64(s): r = [] x = len(s) % 3 if x: s = s + "\0" * (3 -...
Python
1
from typing import Any, Dict, Optional from pydantic import BaseModel, model_validator class PemissionConfig(BaseModel): default_permissions: str class PermissionModel(BaseModel): methods: Optional[list[str]] = [] endpoints: Optional[list[str]] = [] pages: Optional[list[str]] = [] rights: Optio...
Python
1
# server/mcp_hub/slack/generate_slack_token.py # Setup # Create a Slack App: # Visit the Slack Apps page: https://api.slack.com/apps # Click "Create New App" # Choose "From scratch" # Name your app and select your workspace # Configure User Token Scopes: Navigate to "OAuth & Permissions" and add these scopes: # chann...
Python
1
name.as_snake_case().len() + 2); // Writing to String never fails write!(res, "--{}", switch.name.as_snake_case()).unwrap(); res } } pub(crate) fn param_short(param: &::config::Param) -> Option<String> { let abbr = param.abbr?; let mut res = Strin...
Rust
0
#[repr(u32)] pub enum DriverType { Unknown = D3D_DRIVER_TYPE_UNKNOWN, Hardware = D3D_DRIVER_TYPE_HARDWARE, Reference = D3D_DRIVER_TYPE_REFERENCE, Null = D3D_DRIVER_TYPE_NULL, Software = D3D_DRIVER_TYPE_SOFTWARE, Warp = D3D_DRIVER_TYPE_WARP, } #[derive(Clone, Copy, Debug)] #[repr(u32)] pub enum ...
Rust
0
# 下一个不是GLY,此时优化最后两个原子 constrain_idx.append(dipeptide_length - 2) constrain_idx.append(dipeptide_length - 1) else: # 下一个是GLY,此时优化最后一个原子 constrain_idx.append(dipeptide_length - 1) else: # 下一个...
Python
1
: compression-tester [dir ...]"); exit(1); } let pl = Pipeline::from(args) .configure(PipelineConfig::default().batch_size(1)) .pipe(|out, args| { // walk all of the directories we were passed for arg in args { debug!("Walking into {:?}", arg); ...
Rust
0
description = videoObj.get("desc") userName = videoObj.get("author").get('unique_id') video = Video(awemeId=awemeId, url=url, createTime=createTime, description=description, author=userName) count += 1 if awemeDownload(video=video): ...
Python
1
4); pub const D3D11_IMAGE_KMT_NV: Self = Self(8); } bitflags::bitflags! { # [doc = "[Vulkan Manual Page](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkExternalMemoryFeatureFlagsNV.html) · Bitmask of [`ExternalMemoryFeatureFlagBitsNV`]"] # [doc (alias = "VkExternalMemoryFeatureFlagsNV")] # ...
Rust
0
ip() for part in parts if part.strip()] def _coerce_cover_urls(self, metadata: dict[str, Any]) -> list[str]: cover = metadata.get("cover") or metadata.get("cover_url") if not cover: return [] if isinstance(cover, str): return [cover] if isinstance(cover, list...
Python
1
body_coefficients[q, r, s, p] ) class HaarRandomVectorTest(unittest.TestCase): def test_vector_norm(self): n = 15 seed = 8317 vector = haar_random_vector(n, seed) norm = vector.dot(numpy.conjugate(vector)) self.assertAlmostEqual(1.0 + 0.0j, norm) class RandomS...
Python
1
CTED_PACKAGE: i32 = 2i32; #[doc = "*Required features: 'Win32_System_SystemServices'*"] pub const SECURITY_CAPABILITY_APPOINTMENTS: i32 = 11i32; #[doc = "*Required features: 'Win32_System_SystemServices'*"] pub const SECURITY_CAPABILITY_APP_RID: u64 = 1024u64; #[doc = "*Required features: 'Win32_System_SystemServices'*...
Rust
0
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright 2011 California Institute of Technology. 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 th...
Python
1
shixiseng_Postpayload = json.dumps({ "inuuid": uuid, "group_uuid": usegroup, "stype": "attach", "report_time": "1周内", ...
Python
1
} impl ERRID1R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { ERRID1R::_0001 => 1, ERRID1R::_0010 => 2, ERRID1R::_0011 => 3, ERRID1R::_0110 => 6, ERRID1R::_1010 => 10, ERRID1R::...
Rust
0
= mask_ms[stage_key] mask = (mask > 0.5).to(torch.float32) depth_gt = depth_gt.unsqueeze(1) depth_gt_volume = depth_gt.expand_as(depth_values) # (b, d, h, w) # inverse depth, depth从大到小变为从小到大 if inverse_depth: depth_values = torch.flip(depth_values, dims=[1]) ...
Python
1
size, leaf_node.size()); assert_eq!(serialized_size(&sibling) as usize, sibling.size()); assert_eq!( (size_before as isize + size_delta) as usize, leaf_node.size() ); assert!(sibling.size() <= MAX_LEAF_SIZE); assert!(sibling.size() >= MIN_LEAF_SIZE); ...
Rust
0
# Copyright (c) 2017-2021 Advanced Micro Devices, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of ...
Python
1
if sys.platform == 'darwin': # macOS return memory_usage / (1024 * 1024) else: # Linux return memory_usage / 1024 except Exception: return 0.0 # 便捷函数 def execute_safe_code(code: str, context: Optional[Dic...
Python
1
RTC_VIO Regulation Register"] pub rtc_vio_reg: crate::Reg<rtc_vio_reg::RTC_VIO_REG_SPEC>, _reserved17: [u8; 0x5c], #[doc = "0x1f0 - IC Characteristic Register"] pub ic_chara_reg: crate::Reg<ic_chara_reg::IC_CHARA_REG_SPEC>, #[doc = "0x1f4 - VDD Off Gating Control Register"] pub vdd_off_gating_ct...
Rust
0
> { fn exit(self, ret: T) { self.shared.ret.set(Some(ret)); let prev = self.shared.status.swap(DONE, Release); if prev == WAIT_RECV { let waiting = self.shared.waiting.take().unwrap(); while self.shared.status.load(Relaxed) != WAIT_RECV { waiting.unpa...
Rust
0
"file" => { let mut vm_snapshot_path = url_to_path(&url)?; vm_snapshot_path.push(VM_SNAPSHOT_FILE); // Try opening the snapshot file let vm_snapshot_file = File::open(vm_snapshot_path).map_err(|e| MigratableError::MigrateSend(e.into()))?; ...
Rust
0
# Copyright (c) 2018 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 app...
Python
1
.report_without_path(fct.pos(), Msg::SuperfluousOpen(name)); return; } if cls.parent_class.is_none() { if fct.has_override { let name = ctxt.interner.str(fct.name).to_string(); ctxt.diag .lock() .report_without_path(fct.pos(), Ms...
Rust
0
return true; } for l in 0..s.len() { if dictionnary.contains(&s[..l]) && Self::is_breakable(&s[l..], dictionnary) { return true; } } return false; } pub fn word_break(s: String, word_dict: Vec<String>) -> bool { let dictionnary: HashSet<&s...
Rust
0
p(hub))); //! //! let service = ServiceBuilder::new() //! .layer(SentryLayer::new(|req: &Request| match req.as_str() { //! "hello" => hello.clone(), //! _ => other.clone(), //! })) //! .timeout(Duration::from_secs(30)) //! .service(tower::service_fn(|req: Request| format!("{} world", req...
Rust
0
ntoIterator<Item = OsString>, W: Write>(args :I, config :&mut Config, stdout: W) -> CliResult { let args = args.into_iter().collect::<Vec<_>>(); let Opt::Udeps(opt) = Opt::from_iter_safe(&args)?; let clap_matches = Opt::clap().get_matches_from_safe(args)?; cargo::core::maybe_allow_nightly_features(); match opt.run...
Rust
0
import pytest from uuid import uuid4 from datetime import datetime, timezone from httpx import AsyncClient, ASGITransport from unittest.mock import AsyncMock from app.main import app from app.api.v1.endpoints import order_routes from app.services.order_main_service import OrderMainService from app.domain.schemas.token_...
Python
1
[serde(skip_serializing_if = "Option::is_none")] pub quantity: Option<u64>, /// The type of line item. /// /// One of `sku`, `tax`, `shipping`, or `discount`. #[serde(rename = "type")] pub type_: String, } impl Object for OrderItem { type Id = (); fn id(&self) -> Self::Id {} fn obj...
Rust
0
# Inspired by: https://github.com/huggingface/transformers/blob/v4.34.1/examples/pytorch/language-modeling/run_clm.py import math from typing import TYPE_CHECKING, Optional, List from transformers import DataCollatorForLanguageModeling, Trainer from llmtuner.data import get_dataset, preprocess_dataset, split_dataset ...
Python
1
to %s' % outfile) with open(outfile, 'w') as f: batches = [queries[i: i + args.predict_batch_size] for i in range(0, len(queries), args.predict_batch_size)] for i, batch in enumerate(batches): logger.info( '-' * 25 + ' Batch %d/%d ' % (i + 1, len(batches)) + '-' * 25 ...
Python
1
pub const Il2CppVarType_IL2CPP_VT_VOID: Il2CppVarType = 24; pub const Il2CppVarType_IL2CPP_VT_HRESULT: Il2CppVarType = 25; pub const Il2CppVarType_IL2CPP_VT_PTR: Il2CppVarType = 26; pub const Il2CppVarType_IL2CPP_VT_SAFEARRAY: Il2CppVarType = 27; pub const Il2CppVarType_IL2CPP_VT_CARRAY: Il2CppVarType = 28; pub const ...
Rust
0
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE """ This module defines models, which are classes of objects read from ROOT files. Models must be subclasses of :doc:`uproot.model.Model`, and models for a specific version of a ROOT class must be subclasses of :doc:`uproot.model.Vers...
Python
1
""" Test files dedicated to individual (stand-alone) DataFrame methods Ideally these files/tests should correspond 1-to-1 with tests.series.methods These may also present opportunities for sharing/de-duplicating test code. """
Python
1
::Integer(b)) => a.partial_cmp(b), (Self::String(a), Self::String(b)) => a.partial_cmp(b), (_, _) => None, } } } impl From<bool> for Value { fn from(v: bool) -> Self { Value::Boolean(v) } } impl From<f64> for Value { fn from(v: f64) -> Self { Value::Floa...
Rust
0
""" N개의 수로 이루어진 수열 -> 최대 10개 수와 수 사이에 끼워넣을 수 있는 N-1개의 연산자. 연산자는 +, -, *, / 수와 수 사이에 연산자를 하나씩 넣어 수식을 만들 수 있다. 주어진 수의 순서를 바꾸면 안됌 식의 계산은 연산자 우선 순위를 무시하고 앞에서부터 진행! 나눗셈은 정수 나눗셈으로 몫만 취함 음수를 양수로 나눌 때는 C++14의 기준을 따름 -> 양수로 바꾼 뒤 몫을 취하고, 그 몫을 음수로 바꿈 결과의 최대와 최소를 구하라! """ def dfs(n, i): # n번째 숫자, 계속 연산이 실행되는 첫번째 피연산자 gl...
Python
1
be benchmarked as a stand-alone Merkle::<T>::on_finalize(last_block_number); // Bumping the block number so that we can add cached roots to it System::<T>::set_block_number(curr_block_number); // Adding 100 leaves every block let leaves = vec![Scalar::zero().to_bytes().to_vec(); 100]; Merkle::<T>::add...
Rust
0
from csv import reader import pygame from settings import * from os import walk def import_csv_layout(path): terrain_map = [] with open(path) as map: level = reader(map, delimiter= ',') for row in level: terrain_map.append(list(row)) return terrain_map def import_cut_graphi...
Python
1
} else { unreachable!("cursor is expected to be a map"); } } } use chrono::{DateTime, Utc}; use crossbeam::crossbeam_channel; use err_derive::Error; use influx_db_client::{Client, Point, Precision, Value}; use log::{debug, error, info, warn}; use smart_meter_parser::{protocols::*, Decoder, Pro...
Rust
0
FORMATION_MODULES = Registry({ "BottleneckWithFixedBatchNorm": BottleneckWithFixedBatchNorm, "BottleneckWithGN": BottleneckWithGN, }) _STEM_MODULES = Registry({ "StemWithFixedBatchNorm": StemWithFixedBatchNorm, "StemWithGN": StemWithGN, }) _STAGE_SPECS = Registry({ "R-50-C4": ResNet50StagesTo4, ...
Python
1
HIGH_LEVEL_MATCH_F`"] #[inline] pub fn is_high_level_match_f(&self) -> bool { *self == CFG7R::HIGH_LEVEL_MATCH_F } #[doc = "Checks if the value of the field is `LOW_LEVEL_MATCH_OCC`"] #[inline] pub fn is_low_level_match_occ(&self) -> bool { *self == CFG7R::LOW_LEVEL_MATCH_OCC ...
Rust
0
# coach.py # Copyright (C) 2016 https://github.com/s4w3d0ff # Copyright (C) 2017 https://github.com/metaperl # Copyright (C) 2017 https://github.com/enricobacis # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as publish...
Python
1
""" MOdule to hande power management systems. """ import psutil import time from jadi import component from aj.api.http import get, post, HttpPlugin from aj.auth import authorize from aj.api.endpoint import endpoint from aj.plugins.power.api import PowerManager @component(HttpPlugin) class Handler(HttpPlugin): ...
Python
1