text
string
label_name
string
labels
int64
ist]) # space the images out in proportion to their cumulative distances # to the start/end images centroids_x = (1 - dist) * x0 + dist * x1 centroids_y = (1 - dist) * y0 + dist * y1 return centroids_x, centroids_y def initialize_theta_scale(n_thetas, scales, verbose=False, **kwargs): """Init...
Python
1
value in bitVec_info.items(): for shap_index in shap_index_list: if info_key == shap_index: if len(info_value) == 1: radius = info_value[0][1] rank_atom = info_value[0][0] amap = {} env = Chem.FindAtomEnvironmentOfRadiusN(mol, radiu...
Python
1
let recv_str = std::str::from_utf8(recovered.data()).unwrap(); println!("message: {:?}", orig_str); println!("original data: {:?}", data); println!("error correction code: {:?}", encoded.ecc()); println!("corrupted: {:?}", corrupted); println!("repaired: ...
Rust
0
final_dna.as_mut()[i] = *dna_2_element; } } let new_kitty = Kitty { id: random_hash, dna: final_dna, price: 0u8.into(), gender: Kitty::<T, T>::gender(final_dna), }; Self::mint(sender, random...
Rust
0
8\x0a\xc0.\xa4s\xa7\xa5=.\xf7\ \xdd\xf8\x87\xd6!Ddd\x87\x03+\xadCHel\ ;h\x01\xa0\xe5\xffvY\x05\x1cl\x1dBDF\x17\ z\xc9\xef\x80\xd3\xadsHe\x0c|\x0a@\x05@\xbb\ \x9c\xe6\xbb\xf1\xdd\xd6!D$7'\x93vq\x15\xd9\ b\xd0\x02\xe0\xa5\x85\xc4\x90*\xfa=p\x92u\x08\x11\ \xc9O\xe8%K\x81\x8f[\xe7\x90J\x18\xb8\x00\xd8\xb1\ \x90\x18RE\x87\x...
Python
1
s_group in _g_process_group_map.values(): ring_id = process_group._group_id for rank in process_group._ranks: if rank in rank_to_id_dict: rank_to_id_dict[rank].append(str(ring_id)) else: rank_to_id_dict[rank] = [str(ring_id)...
Python
1
from multimedeval.radgraph.allennlp.data.vocabulary import Vocabulary from multimedeval.radgraph.allennlp.models.model import Model from multimedeval.radgraph.allennlp.modules.text_field_embedders import ( TextFieldEmbedder, ) from multimedeval.radgraph.allennlp.modules.seq2seq_encoders import Seq2SeqEncoder from m...
Python
1
unsafe { AUDIO_ZERO_COUNT = 0; } let mut encoder = Encoder::new( sample_rate, if config.channels() > 1 { Stereo } else { Mono }, LowDelay, )?; let channels = config.channels(); let stream = match config.sample_format() { ...
Rust
0
def get_model_description(model_name): # -------------------------- #Retorna uma string com a descrição detalhada de cada modelo de IA. # -------------------------- descriptions = { "Xception": ( "📘 XCEPTION (Extreme Inception)\n" "================================\n" ...
Python
1
# 2D uzaydaki noktaları temsil eden bir liste oluşturma points = [(2, 3), (0, -1), (4, 5), (-2, 6)] print("Points Listesi:") print(points) import math def euclideanDistance(point1, point2): """ İki nokta arasındaki Öklid mesafesini hesaplar. Argümanlar: point1 (tuple): İlk nokta, (x1, y1) şeklinde. ...
Python
1
""" GradientBoostedTree.py (author: Anson Wong / git: ankonzoid) """ import numpy as np from sklearn.tree import DecisionTreeRegressor class GradientBoostedTreeRegressor: def __init__(self, n_estimators=20, max_depth=5, min_samples_split=2, min_samples_leaf=1): self.n_estimators = n_e...
Python
1
import numpy as np import cvxpy as cp K = 5 # number of missions D = np.array([1.2e5, 4.5e5, 5.2e5, 2.4e5, 1.1e6]) # m V = np.array([8.2e1, 5.5e1, 6.5e1, 7e1, 4.8e1]) # m/s W_pay = np.array([2.5e1, 3.2e1, 3.2e1, 5.7e1, 9.3e0]) # kg W_eng_min = 5 # kg W_eng_max = 50 # kg W_bat_min = 10 # k...
Python
1
H_E = 0x63, MOV_H_H = 0x64, MOV_H_L = 0x65, MOV_H_M = 0x66, MOV_H_A = 0x67, MOV_L_B = 0x68, MOV_L_C = 0x69, MOV_L_D = 0x6a, MOV_L_E = 0x6b, MOV_L_H = 0x6c, MOV_L_L = 0x6d, MOV_L_M = 0x6e, MOV_L_A = 0x6f, MOV_M_B = 0x70, MOV_M_C = 0x71, MOV_M_D = 0x72, MOV_...
Rust
0
#!/usr/bin/python3 """Module for count_words function""" import json import requests def count_words(subreddit, word_list, after='', hot_list=[]): """Function that queries the Reddit API.""" if after == '': hot_list = [0] * len(word_list) url = "https://www.reddit.com/r/{}/hot.json" \ .fo...
Python
1
import tensorflow as tf import os import numpy as np def label_smooth(y, weight=0.9): # requires y to be one_hot! return tf.clip_by_value(y, clip_value_min=(1.0 - weight) / (FLAGS.num_classes - 1.), clip_value_max=weight) def random_flip_left_right(images): images_flipped = tf.reverse(images, axis=[2]) ...
Python
1
views.append(v) else: views += [_extend_view_name(v, r, spec) for r in repeat_strings] p.views = views params_named.append(p) return params_named def _remove_layer_props(chart, subcharts, layer_props): def remove_prop(subchart, prop): # If s...
Python
1
oned glyphs apply_knuth_plass_adjustments(&mut positioned_glyphs, knuth_plass_adjustments); // (9) Align text horizontally (early return if left-aligned) align_text_horz(horz_alignment, &mut positioned_glyphs, &line_break_offsets); // (10) Align text vertically (early return if text overflows) ali...
Rust
0
air for header_row, course_col, credit_col in header_pairs: if not summer and is_summer_above(worksheet, header_row, course_col): continue # Skip this section if 'Summer' is detected above and summer is False row_count = 0 while total_credits < TARGET_CREDIT_HRS and row_count <...
Python
1
on_past' : False, 'email' : ['heli.silva@sirtec.com.br'], 'email_on_failure' : True, 'email_on_retry' : False, 'owner' : 'bob', 'retries' : 2, 'retry_delay' : duration(seconds=5) } with DAG('v2_atesto', default_args = default_args, #default_view="graph", start_date=today...
Python
1
T::parse))` /// /// For ex: /// ```rust /// # use nom_derive::Nom; /// # use nom::{do_parse,IResult,many0,complete,be_u16}; /// # /// # #[derive(Debug,PartialEq)] // for assert_eq! /// #[derive(Nom)] /// struct S { /// a: Vec<u16> /// } /// /// # fn main() { /// let input = b"\x00\x00\x00\x01"; /// let res = S::parse...
Rust
0
import struct import random, string from os import popen4 import time a=open("fichero.dat", "wb") a.write("") a.close() stdin,stdout = popen4(r"EXAMEN_23_64_bits_version_b.exe") print stdin #TIRO 1 --------------------------------------------- tiro_1=struct.pack("<L", 0x41414141) + "\n" cadena = tiro_1 print "E...
Python
1
get_defined_modifiers_as_value(&mut interpreter).unwrap(); let expected = interpreter .execute_in_main_environment(r#"'((2 33 "mod") (3 22 ()))"#) .unwrap(); crate::utils::assert_deep_equal(&mut interpreter, expected, result); } } use bellman::PrimeField; use franklin_crypt...
Rust
0
06\x07\x06#\x22'&5476632\x16\ \x14\x06#\x22'\x22\x014&\x22\x07\x0e\x02\x07\x06\x07\ \x07276766C;(\x0f\x18jo% \ '\x15\x07\x0fyD6\x0a\x01#-wZR\x13\x05\ \x01\x07\x06\x04\x02\x01\x05\x03@\x81-4\x0f\x04@>\ h\x0c\x19\x1f%\x99y\x0c\x06+\x06\x0bA(\x5cj\ \x0e\x11\x128\x19\x05\x1f0\x8c\x93\x08\x1d]\x1a\x0a\x05\ \x0c- \x12\x17+\x...
Python
1
the Sobol experiment runMetaModel(xLola, yLola, "LOLA") # %% # Define a function to plot the different scores def drawScore(score, tag): f = ot.DatabaseFunction(xLola, score) lb = distribution.getRange().getLowerBound() ub = distribution.getRange().getUpperBound() graph = f.draw(lb, ub) final = o...
Python
1
&[asset], ], payer=payer, bump=bump, space=3000)] pub margin_stress_account: ProgramAccount<'info, MarginStressAccount>, #[account(signer)] pub payer: AccountInfo<'info>, pub system_program: Program<'info, System>, pub rent: Sysvar<'info, Rent>, } pub fn handle(ctx: Context<InitMa...
Rust
0
""" build123d enum tests name: test_build_enums.py by: Gumyr date: Feb 2nd 2023 desc: Unit tests for the build123d enums license: Copyright 2023 Gumyr 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...
Python
1
equest = SaveTransactionsRequest::new(txns_to_commit, first_version, ledger_info_with_sigs) .into(); self.client().await?.save_transactions(req).await?; Ok(()) } } /// This trait defines interfaces to be implemented by a storage read client. /// /// There is a 1-1 mappin...
Rust
0
Reader { fn read_remaining_byte(&mut self) -> io::Result<u8> { Ok(self.read_bits(self.buffer_size % 8)? as u8) } fn read_bits(&mut self, mut len: usize) -> io::Result<u64> { assert!(len <= 64); let mut start = 0; let mut result = 0; if self.buffer_size < len { ...
Rust
0
) if result.returncode != 0: return f"Error: Nmap returned non-zero exit code {result.returncode}\nStderr: {result.stderr}" return result.stdout except subprocess.TimeoutExpired: return "Error: Nmap scan timed out after 5 minutes" except FileNotF...
Python
1
at!("{:?}", err), error_msg_ptr, error_msg_max_length); } return -1; } let result = consumer.tokio_runtime.block_on( consumer.consumer.handle_messages::<_, ()>(|commands, shared_memory, message| { let buffer = message.buffer(shared_memory); let mut commands_wra...
Rust
0
tion { debug!( "Deadline missed: {:?} - {:?}", since_last, deadline_duration ); self.requested_deadline_missed_count += 1; changes.push(DataReaderStatus::RequestedDeadlineMissed { count: CountWithChange::start_from(self.requested_deadline_misse...
Rust
0
Ordering::Greater); /// ``` pub trait OrdArray { /// Return ordering between array element at index i and j fn cmp_value(&self, i: usize, j: usize) -> Ordering; } impl<T: OrdArray> OrdArray for Box<T> { fn cmp_value(&self, i: usize, j: usize) -> Ordering { T::cmp_value(self, i, j) } } impl<T:...
Rust
0
import numpy as np from ray.tune import schedulers from hyperopt import hp from ray.tune.suggest.hyperopt import HyperOptSearch scheduler = schedulers.AsyncHyperBandScheduler(time_attr='training_iteration', metric='valid_accuracy', mode='max', ...
Python
1
m' for live feed: ").strip().lower() if mode == 'video': video_path = input("Enter the full path to the video file: ").strip() if video_path: output_path = os.path.join(output_dir, os.path.basename(video_path)) start_time = time.time() process_video(video_path, ou...
Python
1
n on") parser.add_argument("--host", type=str, default="localhost", help="Host to bind to (0.0.0.0 for production)") parser.add_argument("--log-level", type=str, default="INFO", choices=["DEBUG", "INFO", "WARNING", "ERROR"]) args = parser.parse_args() # Update configuration logging.getLogger()....
Python
1
ny]: """Validate component inputs during run_component.""" # NOTE: user can override this method to validate inputs # but we do this by default for convenience return input async def _arun_component(self, **kwargs: Any) -> Any: """Run component (async).""" raise NotI...
Python
1
o'), ], ); } <gh_stars>1-10 //! Console operations for playing the game on the command line. Aiming for bare minimum //! simplicity here and not some fancy term driven app. The console is to verify that the //! engine works. The intended UI will be something else. use std::io; use std::collections::HashSet;...
Rust
0
# -*- coding: utf-8 -*- """ Created on Mon Jan 16 02:56:45 2017 @author: Shabaka """ import re import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt def word_in_text(word, tweet): word = word.lower() text = tweet.lower() match = re.search(word, tweet) if match...
Python
1
#Función sin parámetros y sin retorno def funcion_sin_parametros(): print("Función sin parámetros") funcion_sin_parametros() #Función con parámetros y sin retorno def funcion_con_parametros_sin_retorno(param1, param2): print(f"El primer parámetro es: {param1}, el segundo parámetro es: {param2}") funcion_con_...
Python
1
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, _ class MailActivitySchedule(models.TransientModel): _inherit = 'mail.activity.schedule' def _plan_filter_activity_templates_to_schedule(self): if self.res_model != 'hr.employee': return s...
Python
1
remove TCP port mapping"; "port" => tcp_port, "error" => %e) } } } if let Some(udp_port) = udp_port { match gateway.remove_port(igd::PortMappingProtocol::UDP, udp_port) { Ok(()) => debug!(log, "UPnP R...
Rust
0
ou have set TCONNECT_EMAIL appropriately.') if TCONNECT_PASSWORD == 'password': logging.warn('NO PASSWORD WAS PROVIDED. Ensure you have set TCONNECT_PASSWORD appropriately.') if NS_URL == 'https://yournightscouturl/': logging.warn('NO NIGHTSCOUT URL WAS PROVIDED. Ensure your have set NS_URL appr...
Python
1
''' iOS accelerometer ----------------- Taken from: http://pyobjus.readthedocs.org/en/latest/pyobjus_ios.html \ #accessing-accelerometer ''' from plyer.facades import Accelerometer from pyobjus import autoclass class IosAccelerometer(Accelerometer): def __init__(self): super().__init__() ...
Python
1
# Copyright 2023 The Google Earth Engine Community Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
Python
1
main() -> Result<(), Box<dyn std::error::Error>> { /// let setts = "esdb://localhost:1234?tls=false".parse::<ClientSettings>()?; /// # Ok(()) /// # } /// ``` /// /// You can declare a single-node or a cluster-mode client while only using a connection string. /// For example, you can define a cluster-mode client based ...
Rust
0
n argument require /// this to be true and invalidate the object pointed to by inner. pub is_owned: bool, } impl Drop for ClosingSigned { fn drop(&mut self) { if self.is_owned && !<*mut nativeClosingSigned>::is_null(self.inner) { let _ = unsafe { Box::from_raw(self.inner) }; } } } /// Frees any resources us...
Rust
0
bers(atoms,True) # relax particle? if relax_func is not None: atoms, coordination_numbers, nl, free_positions = relax_func(atoms,coordination_numbers,nl,free_positions,trajectory) # Mask of atoms on surface to calculate ...
Python
1
WHERE stock_code = ? AND (stock_name IS NULL OR stock_name = '' OR stock_name = '-') """, updates) updated_count = cursor.rowcount conn.commit() self.logger.info(f"成功更新{market}数据库 {updated_count} 条记录的股票名称")...
Python
1
} /// Adds the [XPath 1.0 core function library][corelib]. /// /// [corelib]: https://www.w3.org/TR/xpath/#corelib pub fn register_core_functions(context: &mut context::Context) { context.set_function("last", Last); context.set_function("position", Position); context.set_function("count", Count); cont...
Rust
0
over verbatim //! 2. Then change //! let mut deps = mock_dependencies(20, &[]); //! to //! let mut deps = mock_instance(WASM, &[]); //! 3. If you access raw storage, where ever you see something like: //! deps.storage.get(CONFIG_KEY).expect("no data stored"); //! replace it with: //! deps.wit...
Rust
0
from pathlib import Path from typing import Dict, List from dotenv import load_dotenv from fastrtc import ( ReplyOnPause, Stream, get_stt_model, get_tts_model, get_twilio_turn_credentials, ) from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel # Load environment variables load_dotenv...
Python
1
cracked_msg = '' if not scanner.args.no302 and r.status_code == 302: cracked_msg = '[+]%s \t\t{302 redirect}' % data_to_print if r.status_code == 200 and scanner.args.fail and not found_err_tag: cracked_msg = '[+]%s \t\t{%s not found}' % (...
Python
1
format!( "New farm created In seed {}, with existed min_deposit {}", terms.seed_id, farm_seed.get_ref().min_deposit ) .as_bytes(), ); } else { farm_seed = VersionedFarmSeed::new(&terms.seed_id, min_de...
Rust
0
super().__init__() self.labels = labels self.blank = blank def forward(self, emission: torch.Tensor): """Given a sequence emission over labels, get the best path Args: emission (Tensor): Logit tensors. Shape `[num_seq, num_label]`. Returns: List[st...
Python
1
ng_proof.ff), first_move_a: miracl_g2_to_bytes(&sharing_proof.aa), first_move_y: miracl_g1_to_bytes(&sharing_proof.yy), response_z_r: miracl_fr_to_bytes(&sharing_proof.z_r), response_z_a: miracl_fr_to_bytes(&sharing_proof.z_alpha), } } /// Parses a sharing proof into a miracl-compat...
Rust
0
let vec = &mut VecResource::<u32>::new(); vec.add(a, 1); vec.add(b, 2); vec.add(c, 3); let mut iter = vec.iter_mut(); assert_eq!(iter.next(), Some((a, &mut 1u32))); assert_eq!(iter.next(), Some((b, &mut 2u32))); assert_eq!(iter.next(), Some((c, &mut 3u32...
Rust
0
Ok(0) => break Some(()), Ok(count) => { let packets = &mut packets[..count]; for packet in packets.iter_mut() { let delay = me.handler.should_delay(packet); me.handle(packet); ...
Rust
0
y): Array with shape (1, m) containing the correct labels for the input data. - m (int): Number of examples. A (numpy.ndarray): Array with shape (1, m) containing the activated output of the network for each example. Returns: float: Th...
Python
1
is allowed. // // Input parameters are current puzzle (level), number of badges and game state - decreasing sum of // acquired puzzles (level 0 was acquired by all teams, level 1 by 300 teams, level 2 by 200 teams // etc.) // // Returns simple true/false value meaning skips is allowed or not. // // Assumption: there i...
Rust
0
may_block: ::std::option::Option< unsafe extern "C" fn(self_: *mut _cef_write_handler_t) -> ::std::os::raw::c_int, >, } #[test] fn bindgen_test_layout__cef_write_handler_t() { assert_eq!( ::std::mem::size_of::<_cef_write_handler_t>(), 80usize, concat!("Size of: ", stringify!(_ce...
Rust
0
specified in the struct. /// You may wonder how the impl would then be able to use the upvar, /// if it doesn't know it's type? The answer is that the impl is /// (conceptually) not fully generic over Closure but rather tied to /// instances with the expected upvar types: /// /// impl<'b, 'a, T> FnMut() for Closur...
Rust
0
#!/usr/bin/env python from vtkmodules.vtkCommonDataModel import vtkImageData from vtkmodules.vtkFiltersParallel import vtkCutMaterial from vtkmodules.vtkImagingSources import ( vtkImageEllipsoidSource, vtkImageGaussianSource, ) from vtkmodules.vtkRenderingCore import ( vtkActor, vtkPolyDataMapper, v...
Python
1
oc = "Front face"] pub const FRONT: Self = StencilFaceFlags(0b1); #[doc = "Back face"] pub const BACK: Self = StencilFaceFlags(0b10); #[doc = "Front and back faces"] pub const FRONT_AND_BACK: Self = StencilFaceFlags(0x0000_0003); } #[repr(transparent)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd...
Rust
0
# 執行各種檢測 anomalies = [] risk_score = 0.0 # 1. IP 檢查 ip_risk, ip_anomalies = self._check_ip_anomalies(user_id, ip_address) risk_score += ip_risk anomalies.extend(ip_anomalies) ...
Python
1
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys import shutil import argparse import fileinput #https://github.com/BVLC/caffe/issues/861#issuecomment-70124809 import matplotlib matplotlib.use('Agg') BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(BASE_DIR)) from ...
Python
1
ose_attack.defaults.status_codes == Some(true)); assert!(goose_attack.defaults.throttle_requests == Some(throttle_requests)); assert!(goose_attack.defaults.sticky_follow == Some(true)); assert!(goose_attack.defaults.manager == Some(true)); assert!(goose_attack.defaults.expect_workers == ...
Rust
0
et repos using latest build artifacts #[derive(Debug, StructOpt)] #[structopt(setting = clap::AppSettings::DeriveDisplayOrder)] pub(crate) struct RepoArgs { // Metadata about the update #[structopt(long)] /// Use this named repo from Infra.toml repo: String, #[structopt(long)] /// The architectu...
Rust
0
ld2, out_vec, scope); out_vec.push(format!("{}cmpl\t$0, %eax", sep)); out_vec.push(format!("{}movl\t$0, %eax", sep)); out_vec.push(format!("{}setne\t%al", sep)); out_vec.push(format!("{}:", end_label)); } "||" => { let start_label = get_next_label(); let end_l...
Rust
0
); let current_worker = Worker { _id: id, }; thread::spawn(move || { loop { current_waiting_sender.send(id).unwrap(); let mut job = current_job_rx.recv().unwrap(); job(); }...
Rust
0
::fmt::Formatter) -> std::fmt::Result { match *self.p.borrow() { ProtectState::NoAccess => write!(f, "SecureBuffer( {:?} )", "<NO_ACCESS>"), _ => write!(f, "SecureBuffer( {:?} )", *self), } } } impl std::ops::Deref for SecureBuffer { type Target = [u8]; fn deref(&se...
Rust
0
(side=RIGHT, fill=Y) canvas.configure(yscrollcommand=yscroll.set) inner = Frame(canvas) inner.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all"))) canvas.create_window((0,0), window=inner, anchor="nw") header = ["Letter","Shelf (F/L/R)","Lower Bound (...
Python
1
for c in range(channels): channel = img[:, :, c].astype(np.float32) if contrast_scale is not None: adjusted = channel * contrast_scale adjusted = gaussian_filter(adjusted, sigma=(sigma, sigma)) blended = (1.0 - strength) * channel + strength ...
Python
1
from . import test_account_payment_financial_surcharge
Python
1
rror(exc) raise AssertionError("unreachable") # noqa: B904 joined = result.asList() assert len(joined) == 1 return joined[0] def get_expression(match: "Match", skip_checks: bool = False): inner = match["inner"] return inner if skip_checks else parse_expr(inner) def validate_value(value...
Python
1
# non local variables def outerFun(): gname = "Sachin" def innerFun(): nonlocal gname # only local variable can be converted into nonlocal variables gname = "Mr." + gname print("Hello World") print(f"Greetings {gname}") innerFun() print(f"outer :{gname}") outerF...
Python
1
ult<Self> { let bytes = path.as_bytes(); let z = libc::sockaddr_un { #[cfg(any( target_os = "netbsd", target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "openbsd" ))] ...
Rust
0
21, computed_S12, ) = geod._gen_direct( *lat1, *lon1, *azi1, false, *s12, caps::ALL | caps::LONG_UNROLL, ); assert_approx_eq!(computed_lat2, lat2, 1e-13f64); as...
Rust
0
logger.info("未获取到激活数据,保持本地激活状态") result["need_activation_ui"] = False result["status_message"] = "保持本地激活状态" # 强制更新状态一致性,避免重复激活 result["status_consistent"] = True self.activation_status["status_consistent"] = True s...
Python
1
"""We have an existing dictionary that maps US states to their capitals. Print the state capital of Idaho Print all states. Print all capitals. Create a single string 'Alabama -> Montgomery, Alaska -> Juneau, ...' Now we want to add the reverse look up, given the name of a capital what state is it in? Implement the ...
Python
1
/////////// /// The web socket should implement this trait only, when it is in a connected /// state pub trait Closeable { fn close(&mut self) -> Result<(), Error<ErrorCode>>; } /////////////////////////////////////////////////////////////////////////////// /// The web socket can implement this trait if it support...
Rust
0
ns support this kind of pooling. In general, only representations which support pointwise non-linearities do. .. warning :: Even if the input tensor has a `coords` attribute, the output of this module will not have one. Args: in_type (FieldType): the input field type ...
Python
1
the private banner field auto-populates properly """ user = login(self) state = models.State.objects.get(name='Active') idea1 = models.Idea(creator=user, title='Transit subsidy to Venus', text='Aliens need assistance.', state=state) banner1 = models...
Python
1
.unwrap(); let mut type_env = TypeEnvironment::new(); type_env.process_statements(&block).unwrap(); assert_eq!(type_env["x"], Type::NUM); assert_eq!(type_env["y"], Type::NUM); assert_eq!(type_env["head"], Type::NUM); assert_eq!(type_env["tail"], Type::from((Type::NUM, Type::NUM))); assert_e...
Rust
0
iter().filter(|file| file.size() > 0).collect() } pub fn active_files(&self) -> Vec<(Patch, &BundleFile)> { let mut out = Vec::<(Patch, &BundleFile)>::new(); for bundle in self.versions.iter().rev() { for file in &bundle.files { if let Err(i) = out.binary_search_by(|...
Rust
0
#!/usr/bin/python # encoding=utf-8 import logging def initLog(logfile, level=2, verbose=False): ''' 日志记录函数,日志等级默认为2,即INFO级别的日志 verbose - 是否屏幕输出,默认False ''' logLevel = logging.INFO if level == 0: logLevel = logging.NOTSET elif level == 1: logLevel = logging.DEBUG elif level == 2: logLevel = logging.INFO...
Python
1
ic language governing permissions and // limitations under the License. use fns_client::FNSClient; use mesatee_core::config::{get_trusted_enclave_attr, OutboundDesc, TargetDesc}; use std::fs; use std::net::{IpAddr, Ipv4Addr}; use tdfs_external_client::TDFSClient; use tms_external_client::TMSClient; pub(crate) struct ...
Rust
0
String) { self.text = text; } pub fn set_x(&mut self, x: i32) { self.x = x; } pub fn set_y(&mut self, y: i32) { self.y = y; } pub fn set_width(&mut self, width: u32) { self.width = width; } pub fn set_height(&mut self, height: u32) { self.heig...
Rust
0
import numpy as np class NoIntersectionError(Exception): pass # vector (m,n) , m = number of examples, n = dimensionality # a = coordinates of the vector # n = orientation of the vector def intersect(a, n): # default normalisation of vectors n n = n/np.linalg.norm(n, axis = 1, keepdims=True) num_line...
Python
1
ebits does. As a result, if you only need to manipulate the `KEEP_CAPS` flag, you /// may wish to instead use [`get_keepcaps()`] and [`set_keepcaps()`]. /// /// [`get_keepcaps()`]: ./fn.get_keepcaps.html /// [`set_keepcaps()`]: ./fn.set_keepcaps.html const KEEP_CAPS = 0x10; ...
Rust
0
_font_family("\"Webly Sleeky UI\", monospace"), Ok(StyleFontFamily { fonts: vec![ FontId("Webly Sleeky UI".into()), FontId("monospace".into()), ] })); } #[test] fn test_parse_style_font_family_2() { assert_eq!(parse_style_font_family("...
Rust
0
.0]); let out = evaluator.evaluate(&features).unwrap(); assert!((out[0] - 20.0).abs() < 1e-6); assert!((out[1] - 50.0).abs() < 1e-6); assert!((out[2] - 100.0).abs() < 1e-6); } } <filename>spiral-matrix/tests/spiral-matrix.rs<gh_stars>1-10 use spiral_matrix::*; #[test] fn empty_spir...
Rust
0
nv::var("API_KEY") { Ok(api_key) => (api_key, ApiKeyRetrievalMethod::EnvironmentVariable), Err(_) => ( env::args().nth(1).context("pass the api key to either an `API_KEY` environment variable or a command line argument")?, ApiKeyRetrievalMethod::CommandLineArgument, ), ...
Rust
0
AUX_EVCTL:EVSTAT2.AON_BATMON_BAT_UPD"] AON_BATMON_BAT_UPD, #[doc = "AUX_EVCTL:EVSTAT2.AON_RTC_4KHZ"] AON_RTC_4KHZ, #[doc = "AUX_EVCTL:EVSTAT2.AON_RTC_CH2_DLY"] AON_RTC_CH2_DLY, #[doc = "AUX_EVCTL:EVSTAT2.AON_RTC_CH2"] AON_RTC_CH2, #[doc = "AUX_EVCTL:EVSTAT2.MANUAL_EV"] MANUAL_EV, ...
Rust
0
test // // Integrity means that all elements are present after a comparison panics, // even if the order may not be correct. // // Destructors must be called exactly once per element. fn test_integrity() { #[derive(Eq, PartialEq, Ord, Clone, Debug)] struct PanicOrd<T>(T, bool); impl<T> Drop for PanicOrd<T...
Rust
0
''' System commands ''' import subprocess # Local modules from .constants import * def is_safe_to_rmrf(path, verbose=True): ''' Check whether it's safe to 'rm -rf' the given path ''' path = os.path.abspath( os.path.expanduser(path) ) path_directories = [] for directory in path.sp...
Python
1
from langchain_community.retrievers.zilliz import ZillizRetreiver, ZillizRetriever __all__ = ["ZillizRetriever", "ZillizRetreiver"]
Python
1
new(self.func.regs_info.get_phys_reg(GR64::RBP)); let src = MachineOperand::Mem(MachineMemOperand::BaseFi(rbp, slot.clone())); let load = MachineInst::new_simple( mov_rx(self.func.regs_info.arena_ref()[new_reg].reg_class, &src).unwrap(), vec![src], ...
Rust
0
se futures::future::{self, Either}; use crate::block_on; use crate::context; use crate::io_event::IoEvent; use crate::reactor::{Reactor, ReactorLock}; use crate::thread_local::ThreadLocalExecutor; use crate::throttle; use crate::work_stealing::WorkStealingExecutor; /// Runs executors and polls the reactor. /// /// Th...
Rust
0
_name() -> Option<&'static str> { cfg_if! { if #[cfg(all(target_os = "linux", target_arch = "x86_64"))] { Some("kubie-linux-amd64") } else if #[cfg(all(target_os = "macos", target_arch = "x86_64"))] { Some("kubie-darwin-amd64") } else if #[cfg(...
Rust
0
{ use peridot::NativeButtonInput::*; use peridot::NativeButtonInput::Character as C; const KEYBOARD_MAP: &[peridot::NativeButtonInput] = &[ Esc, C('1'), C('2'), C('3'), C('4'), C('5'), C('6'), C('7'), C('8'), C('9'), C('0'), C('-'), C('='), Backspace, C('\t'), C('Q'), C('W')...
Rust
0