text
string
label_name
string
labels
int64
a=input("Enter a Number You Want to Find Squre : ") a=int(a) #to find a squre of area is define a by Abrar shaikh print("area of squre is : ",a*4)
Python
1
.position(|&v| v == 0) .unwrap() as usize]) .unwrap().to_owned())] pub name: String, pub car_number: u8, pub ready_status: ReadyStatus, } #[binread] #[br(little)] #[derive(Debug, PartialEq, Clone)] pub struct LobbyInfo { #[br(temp)] num_p...
Rust
0
Directory, File, Link, Pipe, Socket, CharDevice, BlockDevice, Special, } impl Type { pub fn is_regular_file(&self) -> bool { match *self { Type::File => true, _ => false, } } } /// The file’s Unix permission bitfield, with one entry per bi...
Rust
0
, non_upper_case_globals)] pub const CCW: types::GLenum = 0x0901; #[allow(dead_code, non_upper_case_globals)] pub const CLAMP_READ_COLOR: types::GLenum = 0x891C; #[allow(dead_code, non_upper_case_globals)] pub const CLAMP_TO_BORDER: types::GLenum = 0x812D; #[allow(dead_code, non_upper_case_globals)] pub const CLAMP_TO_...
Rust
0
let mut atk = 0.0; let mut momatk = 0; for dmg in once(tatk).chain( (1..if ctx.get(id, Stat::adrenaline) == 0 { 1 } else { etg::countAdrenaline(tatk) }) .map(|a| ctx.trueatk_adrenaline(id, a)), ) { if delay != 0 { delay -= 1; continue; } momatk += dmg; if !momentum { atk += if let Som...
Rust
0
""" https://en.wikipedia.org/wiki/Rail_fence_cipher """ def encrypt(input_string: str, key: int) -> str: """ Shuffles the character of a string by placing each of them in a grid (the height is dependent on the key) in a zigzag formation and reading it left to right. >>> encrypt("Hello World", 4) ...
Python
1
); keysyms.insert(0x03f9, "uogonek"); keysyms.insert(0x03fd, "utilde"); keysyms.insert(0x03fe, "umacron"); keysyms.insert(0x1000174, "Wcircumflex"); keysyms.insert(0x1000175, "wcircumflex"); keysyms.insert(0x1000176, "Ycircumflex"); keysyms.insert(0x1000177, "ycircumflex"); keysyms.insert(0x1001e02, "Ba...
Rust
0
idx = Index(index_name, using=self.client) idx.settings(**{"index.knn": True}) mapping = Mapping() mapping.field("vec", field.KnnVector(dimension=3)) idx.mapping(mapping) result = idx.create() assert result["acknowledged"] is True field_mapping = idx.get...
Python
1
enoising_end=denoising_frac, guidance_scale=guidance_scale, output_type="latent" if use_refiner else "pil", ).images[0] scheduler = self.pipe.scheduler if use_refiner: self.refiner.scheduler = scheduler image = self.refiner( prompt=...
Python
1
def handler() -> str: return "I'm alive!"
Python
1
// // To regenerate this file, run: // hphp/hack/src/oxidized/regen.sh #![allow(unused_variables)] use super::type_params::Params; use super::visitor_mut::VisitorMut; pub trait NodeMut<P: Params> { fn accept( &mut self, ctx: &mut P::Context, v: &mut dyn VisitorMut<P = P>, ) -> Result<...
Rust
0
{ let file = t!(File::open(&md.0)); let mut rslices = rbufs.iter_mut() .map(|b| b.as_mut()) .collect::<Vec<_>>(); let r = rt.block_on(async { file.readv_at(&mut rslices[..], 0) ...
Rust
0
_, &node) in network.nodes.iter() { graph.add_node(node); } for (&src, &src_node) in network.nodes.iter() { for (dst, &weight) in network.weights.row(src).iter().enumerate() { if weight > 0.0 { graph.add_arc(src_node, network.nodes[&dst], weigh...
Rust
0
} } impl TryFrom<u16> for KeyName { type Error = EncodingError; fn try_from(src: u16) -> Result<Self, Self::Error> { match src { 0x0000 => Ok(KeyName::EnclaveInitToken), 0x0001 => Ok(KeyName::Provision), 0x0002 => Ok(KeyName::ProvisionSeal), 0x0003 =...
Rust
0
, Deserialize), serde(crate = "serde_crate") )] pub struct RationalQuadratic { pub variance: f64, pub lengthscales: Vec<f64>, pub power: f64, } impl RationalQuadratic { pub fn new(variance: f64, lengthscales: Vec<f64>, power: f64) -> RationalQuadratic { RationalQuadratic { powe...
Rust
0
2 = Point::new(x2, y2); self.current_path.rat_quad((self.end_point, 1.0), (p1, w0), (p2, 1.0)); self.end_point = p2; self.end_control_point = p2; } pub fn rat_cubic_to( &mut self, x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f...
Rust
0
x01) << 4); self.w } } #[doc = "LP Software Reset Disable When set, disables the LP software reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LP_SWR_DIS_A { #[doc = "0: LP software reset is enabled"] LP_SWR_DIS_0 = 0, #[doc = "1: LP software reset is disabled"] ...
Rust
0
make_canvas_color(color)); } self.context.begin_path(); self.context .arc( center.0 as f64, center.1 as f64, radius as f64, 0.0, std::f64::consts::PI * 2.0, ) .map_err(|e| DrawingE...
Rust
0
ed_result[trait]) true_dic[prompt][trait].append(true_result[trait]) except: #print("skipped") continue for prompt in range(1,9): trait_list = trait_map[prompt] for trait in trait_list: ...
Python
1
first_column = [] my_hash = {} with open("example.txt", "r") as file: for line in file: columns = line.split() if len(columns) == 2: first_number, second_number = int(columns[0]), int(columns[1]) first_column.append(first_number) my_hash[second_number] = 1 if sec...
Python
1
# Copyright 2019 The TensorFlow 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 applica...
Python
1
digital_signature, content_comitment, key_encipherment, data_encipherment, key_agreement, key_cert_sign, crl_sign, encipher_only, decipher_o...
Rust
0
], log: vec![log("action", "reinvest"), log("bonded", balance.amount)], data: None, }; Ok(res) } pub fn query<S: Storage, A: Api, Q: Querier>( deps: &Extern<S, A, Q>, msg: QueryMsg, ) -> StdResult<Binary> { match msg { QueryMsg::TokenInfo {} => to_binary(&query_token_info(de...
Rust
0
def calculate_npv(initial_investment, discount_rate, cash_flows): npv = -initial_investment # Start with the initial investment (outflow) for t, cash_flow in enumerate(cash_flows, start=1): npv += cash_flow / (1 + discount_rate) ** t return npv def main(): print("Welcome to the NPV Calculator"...
Python
1
raise KeyError(f"未找到用户 {user_id} 的嵌入") return self.embeddings[user_id] def get_all_embeddings(self): """ 获取所有用户的嵌入 返回: 所有嵌入的数组和对应的用户ID列表 """ user_ids = list(self.embeddings.keys()) embeddings = np.array([self.emb...
Python
1
ne.engine) }; assert_eq!(result, 0); Instance { engine: self.engine, } } } /// An instantiated module from our `BenchApi`. pub struct Instance<'a, 'b, 'c, M> { engine: Engine<'a, 'b, 'c, M>, } impl<'a, 'b, 'c, M> Instance<'a, 'b, 'c, M> { /// Turn this instance back int...
Rust
0
char, &'static str)> { None } pub fn default_modifier(self, _arch: InlineAsmArch) -> Option<(char, &'static str)> { None } pub fn supported_types( self, arch: InlineAsmArch, ) -> &'static [(InlineAsmType, Option<Symbol>)] { match (self, arch) { (...
Rust
0
#[doc = "1: Any bytes following the IP payload section of the frame are removed from the frame."] _1, } impl From<PADREM_A> for bool { #[inline(always)] fn from(variant: PADREM_A) -> Self { match variant { PADREM_A::_0 => false, PADREM_A::_1 => true, } } } #[d...
Rust
0
#[doc = "*Required features: `\"Win32_Networking_NetworkListManager\"`*"] pub const NLM_CONNECTION_COST_OVERDATALIMIT: NLM_CONNECTION_COST = 65536i32; #[doc = "*Required features: `\"Win32_Networking_NetworkListManager\"`*"] pub const NLM_CONNECTION_COST_CONGESTED: NLM_CONNECTION_COST = 131072i32; #[doc = "*Required f...
Rust
0
Point::SCSouth => print!("v"), Point::SCEast => print!(">"), } } println!(); } println!(); println!(); }/* * Copyright (c) 2020 TensorBase, and its contributors * All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License")...
Rust
0
Cov+TS+LDA pipeline, we reduce the computation time # in approximately 8 times to the Cov+ElSel+TS+LDA pipeline. print("Averaging the session performance:") print(results.groupby("pipeline").mean("score")[["score", "time"]]) ############################################################################### # Plot Result...
Python
1
""" This example describes how to use the workflow interface to chat. """ # Our official coze sdk for Python [cozepy](https://github.com/coze-dev/coze-py) from cozepy import COZE_CN_BASE_URL from doubaoconfigs import coze_api_token # Get an access_token through personal access token or oauth. coze_api_token = coze_...
Python
1
SimpleAttributeGraph2}; use crate::character::{Character, CharacterName}; use crate::character::character_common_data::CharacterCommonData; use crate::common::item_config_type::{ItemConfig, ItemConfigType}; use crate::common::StatName; use crate::enemies::Enemy; use crate::target_functions::target_function_opt_config:...
Rust
0
#[pyfunction] fn concat_lf(lfs: &PyAny, rechunk: bool) -> PyResult<PyLazyFrame> { let (seq, len) = get_pyseq(lfs)?; let mut lfs = Vec::with_capacity(len); for res in seq.iter()? { let item = res?; let lf = get_lf(item)?; lfs.push(lf); } let lf = polars::lazy::functions::c...
Rust
0
#fmt["Explicit index of non-index type `%s`", ty_to_str(self.tcx, base_cmt.ty)]); } }; ret alt deref_kind(self.tcx, base_cmt.ty) { deref_ptr(ptr) { // (a) the contents are loanable if the base is loanable // and this is a...
Rust
0
ので、360MHzとする) peripheral .RCC .pllcfgr .modify(|_, w| unsafe { w.plln().bits(180) }); // PLL クロック確定(最大180MHzなので、180MHzとする) // ちなみにPはシステムクロック、Rは、QはUSBなど...別々に運用できる peripheral.RCC.pllcfgr.modify(|_, w| w.pllp().div2()); // PLL ON peripheral.RCC.cr.modify(|_, w| w.pllon().o...
Rust
0
error_message, )); } "ValidationException" => { return ListLoggerDefinitionVersionsError::Validation(error_message.to_string()); } _ => {} } } return ListLoggerDefinitionVersion...
Rust
0
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # 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 ...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <|...
Python
1
from transformers import WhisperForConditionalGeneration, WhisperProcessor import librosa from messageHandler import logger class SpeechRecognition: def __init__(self,model='medium'): # self.model_id = 'Pardner/whisper-small-fa' if model == 'small': self.model_id = 'masoudkaviani/whispe...
Python
1
efcount.checked_add(1).expect(" refcount is 64bit. Generating this overflow would require to store _at least_ 18 exabyte of data assuming that a contract consumes only one byte of data. Any node would run out of storage space before hitting this overflow. qed "); } /// Token to be supplied to the gas meter ...
Rust
0
embeddings_tensor.view(embeddings_tensor.size(0), -1) # Flatten the second and third dimensions # embeddings_np = embeddings_flattened.detach().cpu().numpy() # Assuming `embeddings_list` is populated with latent embeddings mean_global_dist, global_distances = compute_latent_curvature(embeddings_list...
Python
1
# 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 u...
Python
1
from celery import Celery import os import sys from os import path from kombu.utils.url import safequote sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) app = Celery( 'scripts', broker="sqs://{aws_access_key}:{aws_secret_key}@".format( aws_access_key=safequote(os.environ.get('CELER...
Python
1
import requests from datetime import datetime, time, date from typing import Any, Dict, List, Optional import streamlit as st from settings import API_URL def fetch_attendance_data(record_date: date) -> Optional[Dict[str, Any]]: """ 指定した日付の勤怠データをAPIから取得する。 Args: record_date (date): 取得対象日付 Re...
Python
1
dsData.append(obj) self._RequestId = params.get("RequestId") class DescribeIntegrationStatisticsRequest(AbstractModel): """DescribeIntegrationStatistics请求参数结构体 """ def __init__(self): r""" :param _TaskType: 任务类型(实时:201,离线:202) :type TaskType: int :param _ProjectId...
Python
1
lone, E> Clone for Custom<F, E> { fn clone(&self) -> Self { Self(self.0.clone(), PhantomData) } } impl<I: Clone, O, F: Fn(&mut StreamOf<I, E>) -> PResult<I, O, E>, E: Error<I>> Parser<I, O> for Custom<F, E> { type Error = E; fn parse_inner<D: Debugger>( &self, _debugger: &m...
Rust
0
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 from __future__ import annotations from VeraGridEngine.IO.base.units import UnitMul...
Python
1
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, tools, _ from odoo.tools import is_html_empty class MailActivity(models.Model): _inherit = "mail.activity" calendar_event_id = fields.Many2one('calendar.event', string="Calenda...
Python
1
use std::io::Read; use hex; use crate::ole::EntrySlice; use super::error::{DataTypeError, Error}; // DataType corresponds to decoded property values // as specified in this document. // https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcdata/0c77892e-288e-435a-9c49-be1c20c7afdb #[derive(Clo...
Rust
0
from dao.personagemDaoSqlite import PersonagemDaoSqlite class TestePersonagemDaoSqlite: personagemDaoSqlite = PersonagemDaoSqlite()
Python
1
import math import subprocess print('''Contributors ============ All contributors (by number of commits): ''') email_map = { # Maintainers. 'git@mikeboers.com': 'github@mikeboers.com', 'mboers@keypics.com': 'github@mikeboers.com', 'mikeb@loftysky.com': 'github@mikeboers.com', 'mikeb@markmedia....
Python
1
StructOpt)] pub struct WatchCommand { /// Tectonic commands to execute on build [default: build] #[structopt(long = "exec", short = "x")] execute: Vec<String>, } impl WatchCommand { fn execute(self, _config: PersistentConfig, status: &mut dyn StatusBackend) -> Result<i32> { let exe_name = crat...
Rust
0
RiemannianGradientOptimizer(circuit=circuit, restriction=restriction, stepsize=0.001) @pytest.mark.slow def test_docstring_example(): """Test the docstring example with Trotterized evolution.""" hamiltonian = qml.Hamiltonian( coeffs=[-1.0] * 3, observables=[qml.PauliX(0), qml.PauliZ(1), qml.Pa...
Python
1
import numpy as np import tensorflow as tf from segmentation.image_utils import rescale_intensity # Import the computation graph and restore the variable values sess = tf.Session() sess.run(tf.global_variables_initializer()) saver = tf.train.import_meta_graph('/home/dsigpu5/bucket/Projects/HeartQC/UKBB/segmentation/t...
Python
1
ox<dyn Model>, EngineError> { match asset.get_type() { AssetType::GltfModel => Ok(Box::new(GltfModel::new(engine, asset, options)?)), _ => Err(EngineError::unsupported_asset_format(asset, "GLTF")), } } #[derive(Debug, Default)] pub struct ModelProperties { pub camera: Option<Camera>, pu...
Rust
0
GttdrCtj|}tj|j}tj||ndS(sCopy mode bits from src to dsttchmodN(R%R&R0tS_IMODER2R6(R+R,R5tmode((su/private/var/folders/vy/31wknkcs30l6xb2fzgwnrkh80000gn/T/pip-build-H4rTmN/pip/pip/_vendor/distlib/_backport/shut...
Python
1
m::IResult; mod parser; use crate::parser::util::parse_size_count; use crate::parser::ParseError; #[derive(Debug)] enum Block { DeviceSource(Vec<Block>), DeviceID([u8; 4]), DeviceName(String), Stream(Vec<Block>), StartTimestamp(u64), TotalSamples(u32), StreamName(String), InputOrientat...
Rust
0
her = std::hash::BuildHasherDefault<rustc_hash::FxHasher>; pub(crate) type FxIndexSet<K> = indexmap::IndexSet<K, FxHasher>; pub(crate) type FxIndexMap<K, V> = indexmap::IndexMap<K, V, FxHasher>; pub(crate) type FxDashMap<K, V> = dashmap::DashMap<K, V, FxHasher>; pub(crate) type FxLinkedHashSet<K> = hashlink::LinkedHash...
Rust
0
cfg_smoothnet_w8 = dict( type='smoothnet', window_size=8, output_size=8, checkpoint='https://openmmlab-share.oss-cn-hangzhou.aliyuncs.com/' 'mmhuman3d/../models/smoothnet/smoothnet_windowsize8.pth.tar?versionId' '=CAEQPhiBgMDo0s7shhgiIDgzNTRmNWM2ZWEzYTQyYzRhNzUwYTkzZWZkMmU5MWEw', device='cpu...
Python
1
} } } pub struct FrameBuilder<'a: 'b, 'b> { fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>, start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>, } impl<'a: 'b, 'b> FrameBuilder<'a, 'b> { #[inline] pub fn add_t(&mut self, t: i64) { self.fbb_.push_slot::<i64>(Frame::VT_T, ...
Rust
0
let ElGamalKeypair { public, secret: _ } = ElGamalKeypair::default(); let msg_0: u64 = 77; let msg_1: u64 = 55; // Subtract two ElGamal ciphertexts let open_0 = PedersenOpening::random(&mut OsRng); let open_1 = PedersenOpening::random(&mut OsRng); let ct_0 = ElGa...
Rust
0
# Genie from genie.metaparser.util.exceptions import SchemaEmptyParserError import logging # Logger log = logging.getLogger(__name__) def get_software_version(device): """ Get software version information of a device Args: device (obj): Device object Returns: str: Device software versi...
Python
1
import torch import torch.nn as nn class BalanceCrossEntropyLoss(nn.Module): ''' Balanced cross entropy loss. Shape: - Input: :math:`(N, 1, H, W)` - GT: :math:`(N, 1, H, W)`, same shape as the input - Mask: :math:`(N, H, W)`, same spatial shape as the input - Output: scalar...
Python
1
'𓅄', 'ꊾ', '\u{2df6}', 'ᢕ', '𐩵', 'এ', '⫦', '𔕗', 'a', 'ᙓ', '❜', '⣘', '⠉', '⚮', '\u{e018d}', '\u{322}', 'ꞌ', '𛀢', '𒀕', 'ꀧ', '\u{e0027}', '𑁦', '\u{1da48}', 'Ⱉ', '𒄛', 'ↂ', '𖹞', 'ḑ', '𒄯', '\u{1cf0d}', '𞸷', '𐿵', 'ዴ', '🥏', '𝝐', '🟨', '𑀠', '\u{e0124}', 'ꗝ', '≉', '𑙘', '⟖', '🦬', '⺃', '㇌', 'Ꟙ', '𝓘...
Rust
0
""" battle of two armies """ #import magent2 def get_config(map_size): gw = magent2.gridworld cfg = gw.Config() cfg.set({"map_width": map_size, "map_height": map_size}) cfg.set({"minimap_mode": True}) cfg.set({"embedding_size": 10}) small = cfg.register_agent_type( "small", ...
Python
1
best_aic = aic best_order = (p, d, q) best_mse = mse best_mae = mae best_model = model_fit except Exception as e: continue return best_order, best_aic, best_mse, best_mae, best_m...
Python
1
assert_eq!(decode(&data, 2, 2), &[0, 1, 1, 0]); } #[bench] fn bench_part_1(b: &mut Bencher) { b.iter(part_1); } #[bench] fn bench_part_2(b: &mut Bencher) { b.iter(part_2); } } //extern crate rustc_serialize; //extern crate hyper; //#[macro_use] extern crate lazy_s...
Rust
0
r def _get_win_folder_with_ctypes(csidl_name): import ctypes csidl_const = { "CSIDL_APPDATA": 26, "CSIDL_COMMON_APPDATA": 35, "CSIDL_LOCAL_APPDATA": 28, }[csidl_name] buf = ctypes.create_unicode_buffer(1024) ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0...
Python
1
import uuid from typing import Annotated from fastapi import APIRouter, Depends from apps.courses.controllers.courses import get_courses, create_course, update_course, get_course, delete_course from apps.courses.schema.courses import GetCoursesQuery, GetCoursesResponse, CreateCourseRequest, GetCourseResponse, \ U...
Python
1
_token(prompt, tokenizer, return_tensors='pt').unsqueeze(0).to(model.device) # prompt for base model streamer = TextStreamer( tokenizer, skip_prompt=True, skip_special_tokens=True ) with torch.inference_mode(): output_ids, speech_ids, audio = model.gener...
Python
1
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.distributed import divide def extra_groups_for_head_shards(ngroups: int, tp_size: int): """Compute the increase in group numbers to account for replication in order to accompany the head shards...
Python
1
_KEY_ID: KeyId = KeyId::max_value(); /// /// 値とそのIDを管理します。 /// /// # Examples /// /// ``` /// // ちなみにドキュメンテーションコメント内のテストは cargo test で実行されます。 /// let mut dictionary = kawaii::Dictionary::new(); /// assert_eq!(dictionary.insert("Alice"), 0); /// assert_eq!(dictionary.insert("Bob"), 1); /// assert_eq!(dictionary.insert(...
Rust
0
File::open(json_file).unwrap(); let reader = BufReader::new(&file); let value: Value = serde_json::from_reader(reader).unwrap(); let json_str = serde_json::to_string(&value).unwrap(); let pipeline: Pipeline = Pipeline { root: serde_json::from_str(&json_str).unwrap(), }; pipeline } u...
Rust
0
#!/usr/bin/env python3 """ Simple test client for NMEA Simulator Connects to the simulator and displays received NMEA messages """ import socket import argparse import sys from datetime import datetime def main(): parser = argparse.ArgumentParser(description='NMEA Simulator Test Client') parser.add_argument(...
Python
1
hape num_gq, num_lq = self.num_queries gquery = self.init_query.weight[:num_gq].unsqueeze(0).repeat(bs, 1, 1) lquery = self.init_query.weight[num_gq:].unsqueeze(0).repeat(bs, 1, 1) gquery_pos = self.query_pos_embedding.weight[:num_gq].unsqueeze(0).repeat(bs, 1, 1) lquery_pos = s...
Python
1
' + window.location.href.substring(5); } // Check SSL certificate document.addEventListener('DOMContentLoaded', function() { // This would need to be implemented server-side for actual validation console.log('SSL Certificate should be vali...
Python
1
"""The pvpc_hourly_pricing integration to collect Spain official electric prices.""" from datetime import timedelta import logging from aiopvpc import BadApiTokenAuthError, EsiosApiData, PVPCData from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_API_TOKEN from homeassistant.co...
Python
1
ment_gap, } def main(opts: argparse.Namespace): data = load_jsonl(opts.data_path) infos = { "comp_rate": 0.0, "variation_rate": 0.0, "hitting_rate": 0.0, "matching_rate": 0.0, "alignment_gap": 0.0, "find_rate": 0.0, } num_samples = 0 for sample...
Python
1
Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 7); self.w.bits |= ((value as u32) & 1) << 7; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 ...
Rust
0
""" Write a function to remove characters from the first string which are present in the second string. assert remove_dirty_chars("probasscurve", "pros") == 'bacuve' """ def remove_dirty_chars(string1, string2): """ :param string1: :param string2: :return: """ result = "" for char in string...
Python
1
l = Editor::<()>::new(); if let Err(_) = rl.load_history("history.txt") { println!("No previous history"); } let mut app = make_subcommand().setting(AppSettings::NoBinaryName); loop { let readline = rl.readline("flipper> "); match readline { Ok(line) => { ...
Rust
0
0, epsilon = 1e-14); /// assert_abs_diff_eq!(x[1].eps1[0], 3.0, epsilon = 1e-14); /// assert_abs_diff_eq!(x[1].eps2[0], 4.0, epsilon = 1e-14); /// assert_abs_diff_eq!(x[1].eps1eps2[(0,0)], 5.0, epsilon = 1e-14); /// ``` fn solve_recursive_inplace<'a>( &self, lu: &LU64, b: &'a...
Rust
0
raw_iter.seek_for_prev(key_3_with_ver_256_2.clone()); assert_eq!(&key_3_with_ver_256_2, &raw_iter.key().unwrap()); assert_eq!(&value_3, raw_iter.value().unwrap()); let n = key_3_with_ver_256_1.len(); raw_iter.seek_for_prev(key_3_with_ver_256_1); assert_eq!(&key_2_with_ver_2_7, &raw_iter.key().unw...
Rust
0
return -1; } hdrbase.write_bytes(0_u8, hdrsize); let mut tmpmsg: msghdr = mem::zeroed(); ptr = hdrbase; if !mhdr.msg_name.is_null() && mhdr.msg_namelen > 0 { tmpmsg.msg_name = ptr as *mut c_void; tmpmsg.msg_namelen = mhdr.msg_namelen; ptr::copy_nonoverlapping(mhdr.msg...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # @author: github.com/tintinweb import sys from optparse import OptionParser from electron_inject import inject import logging logger = logging.getLogger(__name__) if __name__ == '__main__': logging.basicConfig(format='[%(filename)s - %(funcName)20s() ][%(levelname)...
Python
1
xtra_headers if attachments: encoded_attachments: list[dict[str, str]] = [] for filename, content, _subtype in attachments: encoded = base64.b64encode(content.encode("utf-8")).decode("ascii") encoded_attachments.append({"filename": fil...
Python
1
::compare_state( id, &state.Gamepad, &prev_states[id].Gamepad, &tx, ); prev_states[id] =...
Rust
0
[wasm_bindgen] extern "C" { pub type WorkersKvJs; #[wasm_bindgen(structural, method, catch)] pub async fn put( this: &WorkersKvJs, k: JsValue, v: JsValue, options: JsValue, ) -> Result<JsValue, JsValue>; #[wasm_bindgen(structural, method, catch)] pub async fn ge...
Rust
0
conn.cursor() c.execute(f'SELECT * FROM dynasties_{country}') rows = c.fetchall() print(f"ราชวงศ์ใน {country.capitalize()}:") for row in rows: print(f"ID: {row[0]}") print(f"Title: {row[1]}") print(f"NameL: {row[2]}") print(f"Summary: {row[3][:50]}...") pri...
Python
1
ic::Phrase::from_entropy(TEST_KEY, BIP39_LANGUAGE) } #[test] fn derive_test_key_from_test_mnemonic() { assert_eq!(test_mnemonic().entropy(), &TEST_KEY); } #[test] fn derive_test_key_from_test_bip39_phrase() { let mnemonic = mnemonic::Phrase::new(TEST_BIP39_PHRASE, BIP39_LANGUAG...
Rust
0
system_info(), now: std::time::Instant::now(), load_avg_view: LoadAvgView::default() }, Command::none() ) } fn title(&self) -> String { String::from("") } fn subscription(&self) -> Subscription<Message> { iced::time::every...
Rust
0
from src import ModConfig from src.utils.config_utils import get_mod_dst_path from subprocess import Popen print("Running GenerateMod.bat") config = ModConfig.get_instance() dst_path = get_mod_dst_path(config.config_data) try: p = Popen(f"{dst_path}\\GenerateMod.bat", cwd=dst_path) stdout, stderr = p.communicate() ...
Python
1
# 1- Escribe un programa que solicite al usuario su nombre y lo imprima en la pantalla. # Declaro la variable en primer lugar y solicito un nombre # nombre = input("Ingrese un nombre de usuario: ") # print("Nombre de usuario es:", nombre) # 2. Crea un programa que calcule la suma de dos números enteros y lo imprima e...
Python
1
"""🎯 数据提取优化 - 针对特定数据类型优化提取策略""" return f'''优化 {url} 的 {data_type} 数据提取 **优化策略:** 1. 使用 crawl_stealth 避免检测 2. 根据数据类型使用 crawl_smart_batch 优化选择器 3. 对于动态加载数据使用 crawl_dynamic 4. 使用 crawl_with_retry 确保数据完整性 **数据类型优化:** - 如果是产品数据: 重点提取价格、规格、评价 - 如果是文章内容: 重点提取标题、正文、作者、时间 - 如果是联系信息: 重点提取邮箱、电话、地址 - 如果是表格数据: 保持结构化格式 **输...
Python
1
epcopy(pop_s1[i]) pos_new = pop_s1[i][self.ID_POS] * (1 + np.random.normal(0, 1, self.problem.n_dims)) agent[self.ID_POS] = self.amend_position(pos_new, self.problem.lb, self.problem.ub) pop_new.append(agent) pop_new = self.update_target_wrapper_population(pop_new) po...
Python
1
raise ValueError("Los parametros deben ser numericos") def print_state(self,mem:list[int]|None = None) -> None: """ Prints the state of the CPU. Add a list of memory addresses for them to be displayed. For example, to display memory addresses 120 and 130, print_state(["120...
Python
1
import hailtop.batch as hb def gwas(batch, vcf, phenotypes): """ QC data and get association test statistics """ cores = 2 g = batch.new_job(name='run-gwas') g.image('us-docker.pkg.dev/<MY_PROJECT>/1kg-gwas:latest') g.cpu(cores) g.declare_resource_group( ofile={'bed': '{root}.b...
Python
1
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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://w...
Python
1
.0.into(); let rem_multiplied_divided = { let rem = b.clone().rem(million.clone()); // `rem` is inferior to one million, thus it fits into u32 let rem_u32 = rem.saturated_into::<u32>(); // `self` and `rem` are inferior to one million, thus the product is less than 10^12 // and fits into u64 let r...
Rust
0