text
string
label_name
string
labels
int64
ce starting on /dev/ttyUSB0 //! ``` //! //! If no config file is specified, then the service will look at `/etc/kubos-config.toml`. //! An alternative config file may be specified on the command line at run time: //! //! ```bash //! $ nsl-duplex-d2-comms-service -c config.toml //! ``` //! //! # Panics //! //! This serv...
Rust
0
#!/usr/bin/env python # coding: utf-8 import os import numpy as np import pandas as pd import mne import matplotlib.pyplot as plt import xml.etree.ElementTree from xml.etree.ElementTree import parse xml = parse('rawdata\mymontage.xml') root = xml.getroot() mydic = dict() for channel in root.findall('CHANNEL'): labe...
Python
1
_err("Incorrect Patricia Merkle Trie: node marked as extension but path contains leaf flag")); } let mut full_path = prefix.clone(); let mut path_left = pair_path.clone(); full_path.append(&mut path_left); let values = pair.next._get_all_...
Rust
0
and action == GLFW_PRESS: print("SPECULAR") amb = False diff = False spec = True if key == GLFW_KEY_O and action == GLFW_PRESS: powienksz = True else: powienksz = False if key == GLFW_KEY_P and action == GLFW_PRESS: zmniejsz = True else: ...
Python
1
| May")?; writeln!(manifest, " | Jun")?; writeln!(manifest, " | Jul")?; writeln!(manifest, " | Aug")?; writeln!(manifest, " | Sep")?; writeln!(manifest, " | Oct")?; writeln!(manifest, " | Nov")?; writeln!(manifest, " | Dec")?; writeln!(manifest, "type alias Date =")?...
Rust
0
''' cadidate = layer_cadidates[backbone_name] # ----- # # depth checking depth_max = len(cadidate) if depth > depth_max: depth = depth_max # ----- # backbone_func = eval(backbone_name) backbone_ = backbone_func(include_top=False, weights=weights, input_tensor=input...
Python
1
ars, mybounds) except: print(f"Failed to fit transit at phase: {e}") continue for k in myfit.bounds.keys(): print("{:.6f} +- {}".format(myfit.parameters[k], myfit.errors[k])) rprs2 = myfit.parameters['rprs'] ** 2 rprs2err = myfit.parameters['rprs'] *...
Python
1
always one2one & one2many, there will be no duplication let no_duplication = aligns .iter() .all(|align| { match align.compute_cardinality(desc) { Cardinality::O2O => true, Cardinality::O2M => true, _ => false } }); let is_one2one = aligns .iter() .all(|align|...
Rust
0
} } #[derive(Debug, Clone)] pub struct CatchainBlockDataView<'a> { pub prev: CatchainBlockDepView<'a>, // TODO: determine optimal size on stack pub deps: SmallVec<[CatchainBlockDepView<'a>; 4]>, } impl<'a> ReadFromPacket<'a> for CatchainBlockDataView<'a> { fn read_from(packet: &'a [u8], offset: &mut u...
Rust
0
import os import pandas as pd import numpy as np import matplotlib.pyplot as plt exchange_list = [ "binance", "gate", "exmo", "htx", "bybit", "kucoin", "kraken", "okx", "whitebit", "bitget", "bitfinex", "bitmart", "poloniex", "lbank", "latoken", "xt", "bingx", "tokocrypto" ] round_numbers = [10 ** i for i...
Python
1
::alias_to_fqdn; use clap::{AppSettings, Arg}; /// Representation of the application's all configurable values. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Options { /// Aliases to look up. pub aliases: Vec<String>, /// Print more information. /// /// Default: `false`. pub verbose:...
Rust
0
, pub next_order_key: cty::c_int, } #[test] fn bindgen_test_layout__priq_rb() { assert_eq!( ::core::mem::size_of::<_priq_rb>(), 16usize, concat!("Size of: ", stringify!(_priq_rb)) ); assert_eq!( ::core::mem::align_of::<_priq_rb>(), 4usize, concat!("Alignme...
Rust
0
xtern "C" fn wedpr_vcl_verify_sum_balance_in_batch( batch_proof_cstring: *mut c_char, ) -> i8 { let result = panic::catch_unwind(|| { let batch_proof = c_safe_c_char_pointer_to_proto_with_error_value!( batch_proof_cstring, BatchCreditBalanceProof, FAILURE ); ...
Rust
0
️" e.add_field( name="Account Number", value=f"📋 {account_number}", inline=False ) e.add_field( name="Account Balance", value=f"💰 {formatt...
Python
1
()) { self.call_box(args) } } #[cfg(when_coherence_is_fixed)] impl<'a, Args, Result> FnOnce<Args, Result> for Box<FnBox<Args, Result> + 'a> { extern "rust-call" fn call_once(self, args: Args) -> Result { self.call_box(args) } } impl<F, Args, Result> FnBox<Args, Result> for F where F: FnOnce<Args, Resul...
Rust
0
def _rel_shift(self, x, zero_triu: bool=False): zero_pad = torch.zeros((x.size(0), x.size(1), x.size(2), 1), device=x. device, dtype=x.dtype) x_padded = torch.cat([zero_pad, x], dim=3) x_padded = x_padded.view(x.size(0), x.size(1), x.size(3) + 1, x.size(2)) x = x_padded.narrow(2, 1, x_padded.siz...
Python
1
pub reference: u32, pub mask: u32, pub write: bool, } #[derive(Clone, Copy, Debug)] pub enum StencilFunc { Always, Equal, NotEqual, } impl Default for RenderState { #[inline] fn default() -> RenderState { RenderState { blend: BlendState::default(), depth...
Rust
0
t task = ReqTask::Multi(vec![dump_cmd_task, pttl_cmd_task]); let state = Self { inner_task, key, lock_guard, }; let entry_fut = Box::pin(get_data_entry(dump_reply_fut, pttl_reply_fut)); (state, task, entry_fut) } fn gen_dump_resp(key: &[u8]) ...
Rust
0
map(&[], |x| transition_from_sql(x)).unwrap().filter_map(|x| x.ok()).collect(); rows } pub fn get_num_transitions(&self, days: u32) -> u64 { 0 } pub fn last_playlist_key(&self) -> Result<PlaylistKey> { let mut stmt = self.socket.prepare("SELECT Key FROM Playlists ORDER BY Key ...
Rust
0
file(x, y, data, p1, p2, n, algorithm=algorithm) npt.assert_allclose(dist, np.linspace(0, area[1] - area[0], n)) npt.assert_almost_equal(xp, np.zeros_like(xp) + 20) npt.assert_allclose(yp, np.linspace(area[2], area[3], shape[1])[::-1]) npt.as...
Python
1
set_d(arg1: mpf_ptr, arg2: f64); } extern "C" { pub fn __gmpf_set_default_prec(arg1: mp_bitcnt_t); } extern "C" { pub fn __gmpf_set_prec(arg1: mpf_ptr, arg2: mp_bitcnt_t); } extern "C" { pub fn __gmpf_set_prec_raw(arg1: mpf_ptr, arg2: mp_bitcnt_t); } extern "C" { pub fn __gmpf_set_q(arg1: mpf_ptr, arg2:...
Rust
0
push("fixtures"); pathbuf.push("noop"); pathbuf.set_extension("so"); let mint_keypair = Keypair::new(); let test_validator = TestValidator::with_no_fees(mint_keypair.pubkey()); let (sender, receiver) = channel(); run_local_faucet(mint_keypair, sender, None); let faucet_addr = receiver.recv...
Rust
0
fn par_run_kernel( ctx: &Context, bases_h: &[G], exps_h: &[<<G as AffineCurve>::ScalarField as PrimeField>::BigInt], cuda_group_size: usize, ) -> DeviceMemory<Self>; fn par_run_kernel_sync<T>( ctx: &Context, bases_h: &[G]...
Rust
0
Path::new("x"); let path = Path::new(".").join("y"); Ok(dir.join(path).to_path_buf()) } <reponame>Gallium70/lrv-rust-bl #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum MemoryUnit { Byte, HalfWord, Word, DoubleWord, Unknown, } impl MemoryUnit { pub fn to_bytenum(&self) -> usize {...
Rust
0
ssert_eq!(Remap::new(0x8, Ram::<0x1>::new().to_shared()).len(), 0x1); assert_eq!(Remap::new(0x80, Ram::<0x10>::new().to_shared()).len(), 0x10); assert_eq!( Remap::new(0x800, Ram::<0x100>::new().to_shared()).len(), 0x100 ); assert_eq!( Remap::new(0x8000...
Rust
0
x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,0x28,], ct: [0x99,0x6f,0xf3,0x30,0xfc,0x7b,0x69,0xd9,0x01,0x99,0xaa,0x29,0x0e,0xf5,0xd2,0xd4,] }, Aes256Test { key: [0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,...
Rust
0
essage = "" if len(parents) < self.min_parents or len(parents) > self.max_parents: message += f"The model:{model_unique_id} doesn't have the required number of parents.\n Min parents: {self.min_parents}, Max parents: {self.max_parents}. It has f{len(parents)} parents\n" if len(children) < s...
Python
1
th('GJS_')) and (not i.startswith('GDM_')) and (not i.startswith('GIO_')) ) ] # Always keep a minimum of 20 items - there's more opportunity to remove items from the # directory contents listing than the environment variables listing. take_n = max(int(len(items) * summarize_factor...
Python
1
; #[test] fn error_duplicate_field() { let input = r#" struct Data { a: u8, b: u8, b: field, } fn main() -> u8 { 42 } "#; let expected = Err(Error::Semantic(SemanticError::Element( Location::new(5, 5), ElementError::Type(TypeError::Structure(StructureTypeError::DuplicateField ...
Rust
0
#!/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. """ SeeKeR LM Medium Model. GPT2-Medium model fine-tuned on SeeKeR data. """ from parlai.zoo.seeker.seeker_download impo...
Python
1
#!/usr/bin/python import sys import os from netifaces import interfaces, ifaddresses, AF_INET if len(sys.argv) != 4: print "inspired by http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet \n" print "usage: shellmaker.py <ip> <port> <type>\n" for ifaceName in interfaces(): addres...
Python
1
import tkinter from tkinter.messagebox import showinfo as alert from tkinter.messagebox import askyesno as question from tkinter.simpledialog import askstring as prompt import customtkinter ''' nombre:Nelly apellido:Burgos --- Ejercicio: while_08 --- Enunciado: Al presionar el botón ‘Comenzar ingreso’, solicitar media...
Python
1
coding(d_coords=input_dim, d_output=self.vision_width,) self.motion_token_mapper = PerceiverResampler( dim=self.vision_width, depth=self.perceiver_config.depth, dim_head=self.vision_width // 8, heads=8, ...
Python
1
containing image features. Returns: mask_predictions: A tensor of shape [batch_size, num_anchors, num_classes, mask_height, mask_width] representing the mask predictions for the proposals. """ mask_predictions = features for layer in self._mask_predictor_layers: mask_predic...
Python
1
.sigma_s, g: self.g, nx: self.nx, ny: self.ny, nz: self.nz, world_to_medium: self.world_to_medium, density: self.density.clone(), sigma_t: self.sigma_t,...
Rust
0
from GF import GF from constants import Rcon import os def get_sbox_and_verify(x): xinv = int(input(f"inv({x}) > "), 16) assert 0 <= xinv < 256 xinv = GF(xinv) assert x * (x * xinv - GF(1)) == GF(0) return xinv + xinv.lrotate(1) + xinv.lrotate(2) + xinv.lrotate(3) + xinv.lrotate(4) + GF(99) def ke...
Python
1
License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #[macro_export] macro_rules! with_timer { ($timer_name:ident, $($s:stmt);+ $(;)?) => ...
Rust
0
= C0*hyper([a, b], [c], x) + C1*y2 elif (c-a-b).is_integer == False: sol = C0*hyper([a, b], [1+a+b-c], 1-x) + C1*hyper([c-a, c-b], [1+c-a-b], 1-x)*(1-x)**(c-a-b) if sol: # applying transformation in the solution subs = match_object['mobius'] dtdx = simplify(1/(subs.diff(x))) ...
Python
1
ippy::vec_box)] use anyhow::{anyhow, Context, Error}; use serde::Serialize; use swc_common::{ errors::HANDLER, sync::Lrc, FileName, FilePathMapping, Globals, Mark, SourceFile, SourceMap, GLOBALS, }; use swc_ecma_ast::*; use swc_ecma_parser::{parse_file_as_module, EsConfig, Syntax, TsConfig}; use swc_ecma_trans...
Rust
0
rp: usize; let cp: usize; let mut line = String::new(); stdin().read_line(&mut line).expect("can't read input"); let rc_in: Vec::<usize> = line .trim() .split_whitespace() .into_iter() ...
Rust
0
from typing import TYPE_CHECKING, List from usos_api.models import CourseEdition, Grade if TYPE_CHECKING: from usos_api import USOSClient class APIHelper: def __init__(self, client: "USOSClient"): self.client = client async def get_user_end_grades_with_weights( self, current_term_only: ...
Python
1
the other. /// * Both dimention size is different and not 1, these shape cannot be broadcasted. pub fn broadcast_zeros<LhsDim, RhsDim>( lhs: &Tensor<LhsDim>, rhs: &Tensor<RhsDim>, ) -> BroadTensor<LhsDim, RhsDim> where LhsDim: Dimension + DimMax<RhsDim>, RhsDim: Dimension, { let (larger_shape, sm...
Rust
0
nn_den=np.nansum(take_triu(J_den_cp.groupby("w").get_group("NW").T.groupby("w").get_group("NW").values)) nn = nn_num/nn_den ww_num=np.nanmean(take_triu(J_num_cp.groupby("w").get_group("W").T.groupby("w").get_group("W").values)) ww_den=np.nanmean(take_triu(J_den_cp.groupby("w").get_group("W").T.groupby(...
Python
1
crate) const VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER: VkStructureType = 45; pub(crate) const VK_STRUCTURE_TYPE_MEMORY_BARRIER: VkStructureType = 46; pub(crate) const VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO: VkStructureType = 47; pub(crate) const VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO: VkStructureType = 48; pu...
Rust
0
1) plt.ylim(0, None) plt.legend() plt.grid() plt.show() # Q3.3 # visualize weights fig = plt.figure(figsize=(8, 8)) plt.title("Layer 1 weights after initialization") plt.axis("off") grid = ImageGrid(fig, 111, nrows_ncols=(8, 8), axes_pad=0.05) for i, ax in enumerate(grid): ax.imshow(layer1_W_initial[:, i].resha...
Python
1
ule, value_operator=value_module, ) actor = actor_critic.get_policy_operator() critic = actor_critic.get_value_operator() del proof_environment return actor, critic # ==================================================================== # Evaluation utils # ------------------------------...
Python
1
g_if! { if #[cfg(feature = "docs")] { #[doc(hidden)] pub struct ImplFuture<'a, T>(std::marker::PhantomData<&'a T>); macro_rules! ret { ($a:lifetime, $f:tt, $i:ty) => (ImplFuture<$a, io::Result<$i>>); } } else { macro_rules! ret { ($a:lifetime, $f:...
Rust
0
me>src/ppu.rs use std::{ fs::File, io::{BufReader, BufWriter}, }; use serde::{Deserialize, Serialize}; use registers::{Controller, Loopy, Mask, Status}; use crate::savable::Savable; use self::frame::Frame; pub mod frame; mod registers; #[derive(Clone, Copy)] pub struct Rgb(u8, u8, u8); /// NES color pale...
Rust
0
( // Disable loading mode after main loading finishes Option::<MainLoadingMode>::None .transition_system() .with_run_criteria(GlobalMode::MainLoading.on(ModeEvent::Exit)), ), ) ...
Rust
0
de_responses=True) response = r.client_list() except redis.ConnectionError: raise RuntimeError("cannot connect to Redis server") # combine the patching from the configuration file and Redis patch = EEGsynth.patch(config, r) # there should not be any local variables in this function, th...
Python
1
th('"""') or stripped.startswith("'''"): return orig, False # Nessuna riga vuota extra: docstring + newline + codice block = f"{ds}{nl}" return f"{leading}{block}{stripped}", True def make_docstring(lang: str, text: str, selection: str, prompt: str) -> str: """ Fallback embedded (senza L...
Python
1
count and domain in columns `COUNT` and `CATEGORY` axis_labels: The labels of the x-axis and y-axis """ g = sns.FacetGrid( data=df, col='CATEGORY', col_wrap=3, height=4, aspect=1.5, sharex=True, s...
Python
1
def str_str(haystack, needle): """ 在字符串中查找子串第一次出现的位置 :param haystack: str,主字符串 :param needle: str,要查找的子串 :return: int,子串第一次出现的位置,如果不存在返回-1 """ if not needle: return 0 if not haystack: return -1 # 遍历所有可能的起始位置 for i in range(len(haystack) - len(nee...
Python
1
from reports.report_types.dns_report.report import DNSReport from octopoes.models.tree import ReferenceTree def test_dns_report_no_findings(mock_octopoes_api_connector, valid_time, hostname, tree_data_no_findings): mock_octopoes_api_connector.tree = {hostname.reference: ReferenceTree.model_validate(tree_data_no_...
Python
1
ning_curves)) / 50) for i, log_alphas in enumerate(all_learning_curves): if i % subsample == 0: ax.plot(log_alphas, 'o-') ax.set_ylabel("Loss") ax.set_xlabel("Step number") #ax.legend(loc=4) ax = fig.add_subplot(N_figs, 1, 2) ax.set_title("Meta Learning Curve") all_train...
Python
1
umber::Float((*var_198).into()), ); } if let Some(var_199) = &input.notification_channel { let mut object_200 = object.key("NotificationChannel").start_object(); crate::json_ser::serialize_structure_crate_model_notification_channel( &mut object_200, var_199, ...
Rust
0
""" Problem: Move Zeroes to End (In-place) LeetCode Link: https://leetcode.com/problems/move-zeroes/description/ Description: ------------ Given an integer array `nums`, move all `0`s to the end while maintaining the relative order of the non-zero elements. This must be done in-place without making a copy of the array...
Python
1
} /// Create a new cuboid primitive from a vector of component dimensions pub fn new_impl(dim: Vector3<S>) -> Self { let half_dim = dim / (S::one() + S::one()); Self { dim, half_dim, corners: Self::generate_corners(&half_dim), } } /// Get the...
Rust
0
predictions: pred_instances_list = split_instances(pred_instances) if output_file: img_vis = visualizer.get_image() mmcv.imwrite(mmcv.rgb2bgr(img_vis), output_file) elif input_type in ['webcam', 'video']: if args.input == 'webcam': cap = cv2.VideoCa...
Python
1
PAD6_DS1_W { w: self } } #[doc = "Bit 12 - Pad 5 slew rate selection."] #[inline(always)] pub fn pad5_sr(&mut self) -> PAD5_SR_W { PAD5_SR_W { w: self } } #[doc = "Bit 8 - Pad 5 high order drive strength selection. Used in conjunction with PAD5STRNG field to set the pad drive str...
Rust
0
&saved_rotor); } rotor.rotate(); prop_assert_eq!(&rotor, &saved_rotor); } } proptest! { #[test] fn encypher_decypher(rotor in rotor_strategy(), plaintext in character()) { let enciphered = rotor.encipher(plaintext, Direction::Forward).unw...
Rust
0
''' /* * Escribe un programa que muestre cómo transcurre un juego de tenis y quién lo ha ganado. * El programa recibirá una secuencia formada por "P1" (Player 1) o "P2" (Player 2), según quien * gane cada punto del juego. * * - Las puntuaciones de un juego son "Love" (cero), 15, 30, 40, "Deuce" (empate), ventaja....
Python
1
import sys import os from activity import main_activity from utils import json_operation from PyQt5.QtWidgets import QApplication from PyQt5 import QtCore, QtGui if __name__ == '__main__': config_path = os.path.join(sys.argv[0], r"../config.json") if os.path.isfile(config_path) is False: default_conf...
Python
1
############################################################################## # # Copyright (c) 2003 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
Python
1
fn std_map_siphash($b: &mut Bencher) { use std::collections::HashMap; let $map = || HashMap::new(); $body } */ } }; } bench!(new_insert_get_host(new_map, b) { b.iter(|| { let mut h = new_map(); h.insert(HOST, "hyper...
Rust
0
# -*- coding: utf-8 -*- import json from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta import sys import pandas as pd import numpy as np import funciones as Fu #####inicio codigo def get_precio(data,periodo): # data=json.loads('{"fondos":[["8240-6","A",100,"ahorro"...
Python
1
(Duration::from_millis(100)); /// /// let average_cpu_stat = cpu::get_average_cpu_stat().unwrap(); /// /// let cpu_percentage = /// pre_average_cpu_stat.compute_cpu_utilization_in_percentage(&average_cpu_stat); /// /// println!("{:.2}%", cpu_percentage * 100.0); /// ``` #[inline]...
Rust
0
for communication, so a connection must /// be established before sending the message, is possible that an error can occur while /// establishing the connection with the destination socket. /// /// If the connection is established successfully, is possible that a the system can fail while /// writi...
Rust
0
import uvicorn if __name__ == "__main__": uvicorn.main()
Python
1
down, }, )) } fn action_keys(i: &str) -> IResult<ActionKeys> { let (i, jump) = key('j')(i)?; let (i, duck) = key('d')(i)?; let (i, use_) = key('u')(i)?; let (i, attack_1) = key('1')(i)?; let (i, attack_2) = key('2')(i)?; let (i, reload) = key('r')(i)?; Ok(( i, Ac...
Rust
0
# Copyright (c) Facebook, Inc. and its affiliates. import random from collections.abc import Callable from enum import Enum from typing import Callable as TCallable from typing import List FrameTsList = List[int] FrameSelector = TCallable[[FrameTsList], FrameTsList] class FrameSelectionStrategy(Enum): """ F...
Python
1
'Content-Type': 'application/json', } if self.apiKey is not None: headers['IDEX-API-Key'] = self.apiKey if api == 'private': payload = None if method == 'GET': payload = query else: payload = body hea...
Python
1
} } }; } /// I2C error #[non_exhaustive] #[derive(Debug)] pub enum Error { /// Bus error Bus, /// Arbitration loss Arbitration, /// NACK Nack, // Overrun, // slave mode only // Pec, // SMBUS mode only // Timeout, // SMBUS mode only // Alert, // SMBUS mode...
Rust
0
encoding::base64_len(salt_len) + encoding::base64_len(hash_len) } /// Hashes the password and returns the encoded hash. /// /// # Examples /// /// Create an encoded hash with the default configuration: /// /// ``` /// use argon2::{self, Config}; /// /// let pwd = b"password"; /// let salt = b"<PASSWORD>"; /// ...
Rust
0
format(head_name)) # make sure the label2id map is correct custom_label2id = custom_label2id or head_config.get("label2id", None) if custom_label2id: head_config["id2label"] = {int(id_): label for label, id_ in custom_label2id.items()} ...
Python
1
import json import os from todolist import Todolist class Storage: @staticmethod def save_to_file(file_path : str, todo_list: Todolist): with open(file_path, "w") as file: json.dump(todo_list.to_dict(), file, indent=4) print(f"Liste sauvegardée dans {file_path}.") @sta...
Python
1
| -> StrResult { let result: OnCreateResult = unsafe { onCreate( env.get_native_interface() as _, *jactivity as _, *jasset_manager as _, ) }; trace_err!(env.set_field( jout_params, "streamSurfaceHand...
Rust
0
@property def dummy_image(self): batch_size = 1 num_channels = 4 sizes = 16, 16 image = floats_tensor((batch_size, num_channels) + sizes, rng=random. Random(0)).to(torch_device) return image
Python
1
mut W, } impl<'a> WTA_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff); self.w } } impl R { #[doc = "Bits 0:31 - GPIO31-0 write data."] ...
Rust
0
message, sender="user"): bubble_color = "#1976D2" if sender == "user" else "#E3F2FD" text_color = "#fff" if sender == "user" else "#222" anchor = "e" if sender == "user" else "w" padx = (80, 10) if sender == "user" else (10, 80) bubble = ctk.CTkLabel(self.chat_frame, text=message...
Python
1
use tendermint_rpc::{self as rpc, endpoint, Response}; const EXAMPLE_APP: &str = "GaiaApp"; const EXAMPLE_CHAIN: &str = "cosmoshub-2"; fn read_json_fixture(name: &str) -> String { fs::read_to_string(PathBuf::from("./tests/support/").join(name.to_owned() + ".json")) .unwrap() } ...
Rust
0
not is_public) or (not github_host.endswith("github.com")): # If the repository is private or hosted on a github enterprise instance, # then the real links to raw.githubusercontents.com will be short-lived. # In this case, it's better to keep an URL that will redirect to the correct URL just wh...
Python
1
ONE); } if ApproxEq::approx_eq(&radians, &consts::PI_3_FRACT_2, &consts::PRECISION) || ApproxEq::approx_eq(&radians.abs(), &consts::PI_FRACT_2, &consts::PRECISION) { return Some(consts::ONE_MINUS); } // Using Taylor Series // See: https://en.wiki...
Rust
0
elf.voice_sample_rate[voice] = value as u16, 0x6 => self.voice_start_address[voice] = value as u16, 0x8 => self.voice_adsr_low[voice] = value as u16, 0xa => self.voice_adsr_high[voice] = value as u16, 0xc => self.voice_adsr_volume[voice...
Rust
0
recursive_add_children(items, opts, dominator_tree, child, wtr)?; } } Ok(()) } let mut wtr = csv::Writer::from_writer(dest); recursive_add_children(items, &self.opts, &self.tree, items.meta_root(), &mut wtr)?; if let Some(Unr...
Rust
0
# -*- coding: utf-8 -*- """ @Date: 2024/11/19 13:07 @Author: Damian @Email: zengyuwei1995@163.com @File: utils_math.py @Description: 数学公式 """ import math import numpy as np import pandas as pd def log_e(series): # 确保输入是 NumPy 数组 series = series.astype(float) x = series.values # 创建输出数组 result...
Python
1
previous transfers, double buffered. Rxd [ RXD OFFSET(0) NUMBITS(8) ], /// TX data to be transferred. Txd [ TXD OFFSET(0) NUMBITS(8) ], /// Baudrate. Baudrate [ BAUDRATE OFFSET(0) NUMBITS(32) [ Baud1200 = 0x0004F000, // 1200 baud Baud240...
Rust
0
er.final_layernorm" in k and pp == input_pp - 1: new_sd["model"][k] = v if "language_model.decoder.layers" in k: layer_num = int(k.split(".")[3]) # On all pp ranks, megatron starts layer nums from 0! new_layer_num = layer_...
Python
1
orm = transform with np.load(npz_path, allow_pickle=True) as f: data = {key: val for key, val in f.items()} # split data based on mask self.data = {} for (k, v) in data.items(): if k == 'names' or k == 'receptors': self.data[k] = v ...
Python
1
a.plane.z * b.rotor.v.y + a.point.w * b.rotor.v.x + a.plane.x * b.rotor.s, a.plane.z * b.rotor.v.x - a.plane.x * b.rotor.v.z + a.point.w * b.rotor.v.y + a.plane.y * b.rotor.s, a.plane.x * b.rotor.v.y - a.plane.y * b.rotor.v.x + a.point.w * b.rotor.v.z + a.plane.z * b.rotor.s, a.plan...
Rust
0
rsi'] < 30 and not pd.isna(latest['momentum_1h']) and latest['momentum_1h'] < 0: bearish_count += 2 # Más peso para señales bajistas # RSI en zona de venta pero no extrema (más sensible) elif 40 < latest['rsi'] < 60 and not pd.isna(latest['momentum_4h']) ...
Python
1
00 = s[-200:] s2tsd = last200[0:TSD_len] set1, set2 = _sliding_window(s1tsd, s2tsd, TSD_len) tsd_dffset = _get_difference(set1, set2) for i in tsd_dffset: if tsd_dffset[i] < TSD_len * 0.2: seq1 = set1[int(i.split(":")[0])] seq2 = set2[int(i.split(":")[1])] ret...
Python
1
atime: Option::None, mtime: Option::None, ctime: Option::None, fh: Option::None, crtime: Option::None, chgtime: Option::None, bkuptime: Option::None, flags: Option::None, }; assert!(f.setattr(2, new_attrs_none, 0).i...
Rust
0
import RPi.GPIO as GPIO import time from Bipolar_Stepper_Motor_Class import Bipolar_Stepper_Motor from numpy import abs,sqrt def GCD(a,b):#greatest common diviser while b: a, b = b, a%b; return a; def LCM(a,b):#least common multipler return a*b/GCD(a,b); def sign(a): #return the sign of number a ...
Python
1
game_state: game.clone(), }; } let move_to_make: u32 = client_msg.data.parse().unwrap(); game.make_move(move_to_make as usize); Msg { status: Status::Ok, headers: Headers::Read, command: Commands::Reply, game_status: GameStatus::InGame, data: for...
Rust
0
base priority of unsigned transactions. /// /// This is exposed so that it can be tuned for particular runtime, when /// multiple pallets send unsigned transactions. #[pallet::constant] type UnsignedPriority: Get<TransactionPriority>; } #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] ...
Rust
0
rL`dC2k@eJ&4eVl!W=JJ4+k&mAt@gt',FS1JjqKW3aq21:]^kna`mde7kVkN5Nr\ pKUptu)@4*b&?BE_sJMG1=&@`3GBCV]Wg7xwgo7x3El", hash: "$7$96..../....f6bEusKt79kK4wdYN0ki2nw4bJQ7P3rN6k3BSigsK/D$Dsvuw7vXj5xijmrb/N\ OhdgoyK/OiSIYv88cEtl9Cik7", }, { pass: "2vj;Um...
Rust
0
from flask import Flask, abort app = Flask(__name__) @app.errorhandler(404) # [app.Flask] # def errorhandler(self, code_or_exception) # 서버에서 반환하는 HTTP 예외 코드(400번대 이상)나 비즈니스 로직에서 일어나는 exception을 관리할 수 있다 # ex) 모든 404 not found에 대하여 커스텀 404 페이지 리턴(https://github.com/adsfokow 처럼), 모든 Exception에 대하여 로깅 등 def error(e...
Python
1
import random import time def RockPaperScissors(): choice = {1: 'rock', 2: 'paper', 3: 'scissor'} while True: print(''' Enter your Choice: 1. enter "paper" for Paper. 2. enter "rock" for Rock. 3. enter "scissor" for Scissors. ''') user = input("Enter your Choice: ") wh...
Python
1
{ Self::Bracketed => { Error::error("$channels must be an unbracketed list.") } Self::BadSep => { Error::error("$channels must be a space-separated list.") } Self::Missing0 => { Error::error(format!("Missing ele...
Rust
0