text
string
label_name
string
labels
int64
ce(count % chunksize, model_sample_args) for d in self.data_processors: sample_data = d.reverse_convert(sample_data) yield sample_data return generator_sample_caller() def _sample_once( self, count: int, model_sample_args: None | dict[str, Any] =...
Python
1
x.add_steam_folder("/home/test/.steam/steam/".to_string()); x.add_steam_folder("/home/test/.steam/steam/".to_string()); x.add_steam_folder("/home/test/.steam/steam/".to_string()); println!("Profiles:\n"); println!("{}", x.to_string(false)); println!("Steam Folders:\n"); ...
Rust
0
s.path.dirname(__file__), "202401_NFs.zip")) diretorio_dados = settings.get_data_directory() # 3. Valida arquivos de entrada logger.execution_step("Validando arquivos de entrada") file_info = validate_input_files(str(caminho_zip), str(diretorio_dados)) # Exibe w...
Python
1
92to384(pretrained: bool = False, **kwargs) -> SwinTransformerV2: """Swin-L V2 @ 192x192, trained at window 12x12, fine-tuned to 384x384 window 24x24.""" model_args = dict( window_size=24, embed_dim=192, depths=(2, 2, 18, 2), num_heads=(6, 12, 24, 48), pretrained_window_sizes=(12, 12, 12, 6)) ...
Python
1
context_encoder=context_encoder, decoder=decoder, get_alibi_bias=alibi_bias_fn, ) def convert_padding_mask(self, x, padding_mask): def get_feat_extract_output_lengths(input_lengths: torch.LongTensor): """ Computes the output length of the convolution...
Python
1
st PROP_START_TIME: u32 = 16u32; #[doc = "*Required features: `\"Win32_Networking_WinSock\"`*"] pub const PROP_VERSION: u32 = 8u32; #[doc = "*Required features: `\"Win32_Networking_WinSock\"`*"] pub const PROTECTION_LEVEL_DEFAULT: u32 = 20u32; #[doc = "*Required features: `\"Win32_Networking_WinSock\"`*"] pub const PRO...
Rust
0
NLEN] = [0x82F5C030B0A801, 0x68, 0x0, 0x0, 0x0]; pub const CURVE_COF: [Chunk; NLEN] = [0x1, 0x0, 0x0, 0x0, 0x0]; pub const CURVE_CRU: [Chunk; NLEN] = [ 0x1C0A24A3A1B807, 0xD79DF1932D1EDB, 0x40921018659BCD, 0x13988E1, 0x0, ]; pub const CURVE_PXA: [Chunk; NLEN] = [ 0x2616B689C09EFB, 0x539A12B...
Rust
0
derive(Copy, Clone)] pub union hv_partition_processor_xsave_features { pub __bindgen_anon_1: hv_partition_processor_xsave_features__bindgen_ty_1, pub as_uint64: __u64, } #[repr(C, packed)] #[derive(Default, Copy, Clone)] pub struct hv_partition_processor_xsave_features__bindgen_ty_1 { pub _bitfield_align_1:...
Rust
0
""" Boyer-Moore string-search algorithm. Author: Wenru Dong """ from typing import List, Tuple SIZE = 256 def _generate_bad_character_table(pattern: str) -> List[int]: bc = [-1] * SIZE for i, char in enumerate(pattern): bc[ord(char)] = i return bc def _generate_good_suffix_table(patter...
Python
1
class Historia: historia : str = [] opciones : str = [] puntero : int matriz_hist_op : int = () def __init__(self): self.puntero = 0 self.opciones = ["Tomar el camino de la izquierda", "Tomar el camino de la derecha", "Avanzar", "Atacar"] self.historia = ["Bienvenido...
Python
1
Park, { // Ensures the run queue is placed back in the `BasicScheduler` instance // once `block_on` returns.` struct Guard<'a, P: Park> { context: Option<Context>, scheduler: &'a mut BasicScheduler<P>, } impl<P: Park> Drop for Guard<'_, P> { fn drop(&mut self) { ...
Rust
0
info!("Shutting down application"); closing::close(); }); // We only support running once so this should never panic. // If there is a legitimate use for activating twice, send on the other channel. // There are also cyclical references that are annoying to clean ...
Rust
0
write!(f, "DOMHTMLBaseFontElement") } } use criterion::{measurement::Measurement, BenchmarkGroup, BenchmarkId, Criterion, Throughput}; use simdutf8::basic::from_utf8 as basic_from_utf8; use simdutf8::compat::from_utf8 as compat_from_utf8; use std::str::from_utf8 as std_from_utf8; #[cfg(feature = "simdjson"...
Rust
0
file_path: Path to source file Returns: True if supported, False otherwise """ try: language = detect_language(file_path) return language != "unknown" except Exception as e: logger.error(f"Error checking language support: {e}") return False def ...
Python
1
= match timeout(self.locktimeout, self.rib.read()).await { Ok(r) => r, Err(_) => { return Response::builder() .status(StatusCode::from_u16(408).unwrap()) .header("Content-type", "text/plain") .body("Operation timed out"...
Rust
0
#[doc = "Reader of field `ABTOINTCLR`"] pub type ABTOINTCLR_R = crate::R<bool, ABTOINTCLR_A>; impl ABTOINTCLR_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ABTOINTCLR_A { match self.bits { false => ABTOINTCLR_A::NO_IMPACT_, true => ...
Rust
0
') best_next_actions = q_values_masked.argmax(dim=1) best_next_dist = next_dist_target[torch.arange(states.size(0)), best_next_actions, :] Tz = rewards.unsqueeze(1) + gammas.unsqueeze(1) * self.support.unsqueeze(0) * ( ~dones).unsqueeze(1).float() Tz...
Python
1
ml = nvml(); test_with_device(3, &nvml, |device| { device.samples(Sampling::ProcessorClock, None)?; Ok(()) }) } #[test] fn field_values_for() { let nvml = nvml(); test_with_device(3, &nvml, |device| { device.field_values_for(&[ ...
Rust
0
UNIT } } fn aged_brie_handler(item : &mut Item) -> i32{ if item.sell_in < MIN_SELL_IN { item.quality + (QUALITY_UNIT * 2) } else { item.quality + QUALITY_UNIT } } fn no_op_handler(_ : &mut Item) {} fn generic_handler(item : &mut Item) -> i32 { if item.sell_in < MIN_S...
Rust
0
= D3DDECLUSAGE::SAMPLE; pub const MAXD3DDECLUSAGEINDEX: ::DWORD = 15; pub const MAXD3DDECLLENGTH: ::DWORD = 64; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DDECLMETHOD { DEFAULT = 0, PARTIALU, PARTIALV, CROSSUV, UV, LOOKUP, LOOKUPPRESAMPLED, } pub const MAXD3DDECLMETHOD: D3DDECLME...
Rust
0
import requests, re,ssl , os , sys import urllib.request import urllib.error from host import host class bticinoExploit: def biticinoExploit(self): pass def bticinoBruteForce(self): ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) path = os.path.abspath(os.path.dirname(sys.argv[0])) upH...
Python
1
ersion="1.0" encoding="utf-8" ?>"###; pub const VIEWS_ROOT: &str = "themes"; <gh_stars>10-100 use std::io::stdin; use std::process; fn main() { let stdin = stdin(); let mut line = String::new(); stdin.read_line(&mut line).unwrap(); println!("{}", line); process::exit(line.trim().parse().unwrap()); ...
Rust
0
from branca.element import MacroElement from jinja2 import Template from folium.elements import JSCSSMixin from folium.utilities import parse_options class GroupedLayerControl(JSCSSMixin, MacroElement): """ Create a Layer Control with groups of overlays. Parameters ---------- groups : dict ...
Python
1
from hippy.mapdict import Terminator class FakeClass(object): pass klass = FakeClass() class TestMapdictDirect(object): def test_simple(self): t = Terminator(klass) assert t.lookup("name") is None new_attr = t.add_attribute("name") a1 = new_attr.lookup("name") assert a...
Python
1
# 读文件 import json from specification_generation.rule_assembly import is_key_for_time, is_key_for_price, is_key_for_quantity import re def mydsl_to_rules(s): """读文件并解析, 将常量写入defines, 变量写入vars, 规则写入rules""" defines = dict() # defines = {"交易结果": ['已申报', '未申报'], } vars = dict() # vars = { # '4.1.1': {'中标...
Python
1
def message_mutation(self, message: Message) -> Message: message = copy.deepcopy(message) if 'labels' in message: labels = message['labels'] text = message['text'] new_labels = [] flip = hashlib.md5(text.encode('utf8')).digest()[0] < self.noise_level ...
Python
1
reinforcements_gas_interviewers -> overcurrent_crowns_misalinement' '# reinforcements_gas_interviewers -> overcurrent_crowns_misalinement' g3kicjedeq9 //= ad5iikxbajr @(vpsusq4uwgk := noqgwqn0vnj) @{wnrwxny1agz} @(yield from 0.0) def hahc95ywx6v(t9bdqf9x_9e, yg73lyhvszl: gy3h6kbw8qf, n2iir39vdk0: kna87dv1t6a): ...
Python
1
import pbk from args_man import parse_args from bitcoin.core import CBlock def main(): args = parse_args() chain_man = pbk.load_chainman(args.datadir, args.chain_type) for block_index in pbk.block_index_generator(chain_man, start=args.start_height, end=args.end_height): block_data = chain_man.read_...
Python
1
train_losses: List of training losses val_losses: List of validation losses val_metrics: List of validation metrics (optional) metric_name: Name of the validation metric (optional) title: Plot title Returns: Matplotlib figure """ fig, ax1 = plt.subpl...
Python
1
} } impl From<u8> for Es { #[inline] fn from(other: u8) -> Self { Es(other) } } impl ::core::fmt::Display for Es { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Es { fn fmt(&self, f: &mut ::core::fmt::Fo...
Rust
0
tmp = [ t[1:] for t in tmp ] # remove first action (1 from 1st half; 2 from 2nd half) # split into two halves n_half = int(len(tmp) / 2) first_half = tmp[:n_half] second_half = tmp[n_half:] # c...
Python
1
import os import torch.nn as nn import numpy as np import torch from datasets import ImageNet from torch.utils.data import DataLoader import argparse from tqdm import tqdm torch.manual_seed(0) np.random.seed(0) def main(resolution=256): parser = argparse.ArgumentParser() parser.add_argument('path') args =...
Python
1
ope { mass_number: 263, mass: UncertainFloat::new(263.111_39_f64, 0.000_39_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, ] } } <filename>src/deploy.rs //! this fi...
Rust
0
========================================================= def expert_reasoning_node(state: ExpertSystemState) -> Dict[str, Any]: """专家推理过程节点 WHY - 设计思路: 1. 需要基于问题和知识进行专业推理 2. 需要明确记录推理过程的每一步 3. 需要考虑可能的替代推理路径 HOW - 实现方式: 1. 提取问题、所需信息和相关知识 2. 使用思维链(CoT)方式引导LLM推理 3. 记录详细的推理步骤和...
Python
1
empty() { None } else { Some(args.trim()) }, contents, ), )) } #[test] fn parse() { use nom::error::VerboseError; assert_eq!( parse_block_element_internal::<VerboseError<&str>>( r#"#+BEGIN_SRC #+END_SRC"# ...
Rust
0
| w.$i2cXrst().clear_bit()); Self::new(i2c, pins, freq, clocks) } } }; } hal!(I2C1, enr, rstr, i2c1, i2c1en, i2c1rst); hal!(I2C2, enr, rstr, i2c2, i2c2en, i2c2rst); hal!(I2C3, enr, rstr, i2c3, i2c3en, i2c3rst); // This peripheral is not present on // STM32L471XX and STM32L431XX...
Rust
0
import random import string from datetime import datetime, timedelta import pytest from waybackpy.availability_api import WaybackMachineAvailabilityAPI from waybackpy.exceptions import ( ArchiveNotInAvailabilityAPIResponse, InvalidJSONInAvailabilityAPIResponse, ) now = datetime.utcnow() url = "https://exampl...
Python
1
#!/usr/bin/python3 # 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 ag...
Python
1
, smithy_types::instant::Format::DateTime ) .map_err(|_|smithy_xml::decode::XmlError::custom("expected (timestamp: `com.amazonaws.elasticache#TStamp`)")) ? ) ; builder ...
Rust
0
if self.cells[i + self.dim - 1].alive { n = n + 1; } } }; if x < self.dim - 1 { // Check right if self.cells[i + 1].alive { n = n + 1; } // Check above right if y...
Rust
0
from dataclasses import dataclass, field from .base_backbone_config import BaseBackboneConfig from typing import Union, List, Optional from torch import nn @dataclass class MLPBackboneConfig(BaseBackboneConfig): input_dim: Optional[int] = field(default=None) hidden_dims: Union[int, List[int]] = field(default=...
Python
1
import time import sys def slp(): time.sleep(1) def act(): return input("Which Avenger do you want to be? (Hulk, Iron Man, Captain America, Antman)") def hulk(): print("You are Hulk now!") slp() print("You ran and jump 30 meters high to the house of the wizard \"Ancient One\" trying to get the Ti...
Python
1
# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction # Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han # International Conference on Computer Vision (ICCV), 2023 from efficientvit.apps.trainer.run_config import RunConfig __all__ = ["ClsRunConfig"] class ClsRunConfig(RunConfig): l...
Python
1
import jax import jax.numpy as jnp from jax.typing import DTypeLike data_type: DTypeLike = jnp.float32 nodes = jnp.linspace(-1, 1, 4, dtype=data_type) values = nodes ** 3 evaluation_points = jnp.array([-1, -0.5, 0, 0.5, 1]) n: int = len(nodes) m: int = len(evaluation_points) # Initialize values array with function ...
Python
1
TokenStream2::new(); // extra genesis if let Some(eg) = extra_genesis { for ex_content in eg.content.content.lines.inner.iter() { match ex_content { AddExtraGenesisLineEnum::AddExtraGenesisLine(AddExtraGenesisLine { attrs, extra_field, extra_type, default_value, .. }) => { ...
Rust
0
_date_second_split = booking_date_second.split('-') booking_date_second_nulls_off = [] for _ in booking_date_second_split: booking_date_second_nulls_off.append(int(_.lstrip('0'))) booking_date_second_nulls_off = str(booking_date_second_nulls_off) total_days = (datetime.date(*...
Python
1
} log_reports.push(LogReport { test_time: start_time.elapsed(), anomalies, source, index_name: index_name.clone(), ...
Rust
0
te Button if st.sidebar.button("Generate Game Design Document"): if usage_count < 2 or user_api_key: # Generate content based on inputs environment_text = generate_game_environment(environment) protagonist_text = generate_protagonist(protagonist) antagonist_text = generate_antagonist...
Python
1
import logging import os import math import hydra import torch import wandb from peft import get_peft_model, LoraConfig from rich import traceback from rich.logging import RichHandler from PIL import Image import torch.nn.functional as F from transformers import ( AutoProcessor, AutoModelForCausalLM, Pali...
Python
1
O_INT64 | ROUND_NUMERIC | GENMAP_EMPTY | GENMAP_INSERT | GENMAP_LOOKUP | GENMAP_DELETE | GENMAP_KEYS | GENMAP_VALUES | GENMAP_SIZE | EQUAL_TYPE_REP | EQUAL | LESS_EQ | LESS | GREATER_EQ | GREATER | TEXT_TO_UPPER | TEXT_TO_LOWER | TEXT_SLICE | TEXT_SLICE_INDEX | TEXT_CONTA...
Rust
0
from crewai import Agent, Crew, Process, Task # type: ignore from crewai.project import CrewBase, agent, crew, task # type: ignore # If you want to run a snippet of code before or after the crew starts, # you can use the @before_kickoff and @after_kickoff decorators # https://docs.crewai.com/concepts/crews#example-cre...
Python
1
t[face_id][1] island_area *= 100 color = utils.Value_To_Color(island_area, bake_vc_min_space, bake_vc_max_space) for face_id in uv_island: for loop in bm.faces[face_id].loops: loop[bm.loops.layers.color.active] = color elif td.bake_vc_mode == "TD_ISLANDS_TO_VC": for u...
Python
1
ped, we attempt to complete the writing, but //! ignoring the errors. //! //! ```rust //! use martian_filetypes::{FileTypeIO, LazyFileTypeIO, LazyWrite}; //! use martian_filetypes::bin_file::BincodeFile; //! use martian_filetypes::lz4_file::Lz4; //! use martian::Error; //! use serde::{Serialize, Deserialize}; //! //! f...
Rust
0
.chain(std::io::stderr()) .apply(); // Ensure that logger was dispatched match result { Ok(_) => trace!("Logging as been initialized!"), Err(error) => { eprintln!("Error initializing fern logging: {}", error); exit(-1); } } } /// The main entr...
Rust
0
id`) and which faulty behavior /// that the node exhibited ('kind'). #[derive(Clone, Debug, PartialEq)] pub struct Fault<N, F: Fail> { /// The faulty node's ID. pub node_id: N, /// The kind of fault the node is blamed for. pub kind: F, } impl<N, F> Fault<N, F> where F: Fail, { /// Creates a new...
Rust
0
\n"); } #[test] fn unl_test_g2() { // Abstraction elimination from `d`.*i assert_evals_to!("`r```s`kd``s`k.*`kii", "\n"); assert_evals_to!("`r```s`kd`k`.*ii", "*\n"); assert_evals_to!("`r``k`d`.*ii", "\n"); assert_evals_to!("`r```si``s`k.*`kid", "\n"); assert_evals_to!("`r```si`k`.*id", "*\n");...
Rust
0
import json import boto3 import base64 sns_client = boto3.client('sns', region_name='us-east-1') FASTEST_LAP = None def lambda_handler(event, context): global FASTEST_LAP for record in event['Records']: payload = base64.b64decode(record['kinesis']['data']) data = json.loads(payload) ...
Python
1
security /// reasons. passwd, pw_passwd; /// Get the user's "GECOS" field. /// /// This sometimes records information about the user. #[cfg_attr(docsrs, doc(cfg(not(all(target_os = "android", target_pointer_width = "32")))))] #[cfg(not(all(target_os = "android", ...
Rust
0
# -*- coding: utf-8 -*- import maya.cmds as cmds ''' obsolete def fit_ground(): #select all the ctrls and last select the ground mesh drive_curves = [] proj_curves = [] locs = [] sel_list = cmds.ls(sl=True) for sel in sel_list[:-1]: #loop in objects #f...
Python
1
s from . import _internal from . import _dtype from . import _methods __all__ = ['char', 'rec', 'memmap'] __all__ += numeric.__all__ __all__ += fromnumeric.__all__ __all__ += rec.__all__ __all__ += ['chararray'] __all__ += function_base.__all__ __all__ += machar.__all__ __all__ += getlimits.__all__ __all__ += shape_ba...
Python
1
then files items = sorted(path.iterdir(), key=lambda x: (not x.is_dir(), x.name)) for item in items: if item.is_dir(): branch = tree.add(f"[bold cyan]{item.name}/[/bold cyan]") _build_directory_tree(item, branch) else: # Color differently based on file exten...
Python
1
"""Outra estrutura fundamental é o dicionário, que associa valores a chaves e permite a rápida recuperação do valor correspondente a uma determinada chave: """ empty_dict = {} empty_dict2 = dict() grades = {"Joel": 80, "Tim": 95} print(f'Pythonic: {empty_dict}\n', f'menos Pythonic: {empty_dict2}\n' f'dici...
Python
1
e-local], [type=month], [type=time], [type=week] ) ):not([readonly], :disabled), html|*:is([contenteditable=""], [contenteditable="true" i]) ''' ).process_selectors(flags=FLG_PSEUDO | FLG_HTML) # CSS pattern for `:read-only` CSS_READ_ONLY = CSSParser( ''' ...
Python
1
from kairon.shared.events.data_objects import ExecutorLogs class ExecutorProcessor: @staticmethod def get_executor_logs(bot: str, start_idx: int = 0, page_size: int = 10, **kwargs): """ Get all executor logs data . @param bot: bot id. @param start_idx: start index @par...
Python
1
""" Classes from the 'Pasteboard' framework. """ try: from rubicon.objc import ObjCClass except ValueError: def ObjCClass(name): return None def _Class(name): try: return ObjCClass(name) except NameError: return None PBDataTransferMonitor = _Class("PBDataTransferMonitor") P...
Python
1
#[doc = "Register SC `reset()`'s with value 0"] impl crate::ResetValue for super::SC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `LDOK`"] pub type LDOK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LDOK`"] pub struct LDOK_W<'a>...
Rust
0
inst: The instruction instance to match against the keys. :type inst: any :param instclass: A descriptive name of the instruction class, used in error messages. :type instclass: any :return: The value corresponding to the only matching key in the multidict. :rtype: any :raises UnknownInstruction...
Python
1
e, 1), self.center_sampler, same_on_batch)) sign = torch.where( _adapted_rsampling((batch_size, 1, 1, 1), self.sign_sampler, same_on_batch) >= 0.0, torch.tensor(1.0, device=_device, dtype=_dtype), torch.tensor(-1.0, device=_device, dtype=_dtype), ) # Generat...
Python
1
#banking system balance = 50000 Loan_Amount = balance / 2 def BankAccount(): print("******Welcome to your Bank Account******* ") Account =print(f"Your Current balance is : {balance}") BankAccount() while True: Account_setting = int(input(f"For\n1: Deposit \n2: Withdraw \n3: Exit \n4: Loan\n")) if ...
Python
1
from dash import Dash, dcc, html, Input, Output, Patch, MATCH, ALLSMALLER, callback import pandas as pd df = pd.read_csv( "https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv" ) app = Dash(__name__, suppress_callback_exceptions=True) app.layout = html.Div( [ html.Button("Add Fi...
Python
1
'particles / (s cm^2 sr MeV/n)': 1 / (u.cm**2 * u.s * u.sr * u.MeV), 'particles/(s cm2 sr MeV/n)': 1 / (u.cm**2 * u.s * u.sr * u.MeV), '1/(cm**2-s-sr)': 1 / (u.cm**2 * u.s * u.sr), '1/(SQcm-ster-s)': 1 / (u.cm**2 * u.s * u.sr), '1/(SQcm-ster-s)..':...
Python
1
leakyrelu_strategy_non_linearity = ((1, 1), (1, 1)) adapter_layer.shard(strategy_non_linearity=leakyrelu_strategy_non_linearity) self.assertEqual(adapter_layer.mindpet_delta_adapter_block.mindpet_delta_adapter_non_linear.select_op.in_strategy, leakyrelu_strategy_non_linearity) ...
Python
1
# Imports from Libraries import numpy as np from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.model_selection import train_test_split import joblib #___________________________________________Cleaning and Test Sets_______________________________________________ def cleaning(df,cd,stockLocati...
Python
1
new - 新建节点的函数(对第二棵树) degree - 获取节点度的函数(对于第一棵树) copy - 拷贝值函数(参数为两棵树) add - 添加子节点函数(对于第二棵树) """ # 使用 BFS 方式拷贝树 uncopied = queue.Queue() uncopied.put((from_, to_)) while uncopied.qsize(): source, destination = uncopied.get() # ...
Python
1
) -> str: """ Format a group of parameter name suffixes into a loggable string. Args: group (list[str]): list of parameter name suffixes. Returns: str: formated string. """ if len(group) == 0: return "" if len(group) == 1: return "." + group[0] return "....
Python
1
ers(reader), } } /// Retrieve the default filters containing the syscall rules required by `Firecracker` /// to function. The binary file is generated via the `build.rs` script of this crate. fn get_default_filters(basic: bool) -> Result<BpfThreadMap, FilterError> { // Retrieve, at compile-time, the serialized...
Rust
0
let coeffs_slice: &[F] = coeffs.as_ref(); assert!(next_coefficients.len()*2 == coeffs_slice.len()); worker.scope(next_coefficients.len(), |scope, chunk| { for (v, old) in next_coefficients.chunks_mut(chunk) .zip(coeffs_slice.chunks(chunk*2)) {...
Rust
0
ect_validate_caller_addr(self.caller_addrs()); self.expect_query_network_info(rt); if !params.deal_ids.is_empty() { let vdparams = VerifyDealsForActivationParams { sectors: vec![SectorDeals { sector_expiry: params.expiration, deal_ids:...
Rust
0
04, 0x0a, 0x12, 0x04, 0x76, 0x00, 0x78, 0x01, 0x1a, 0x1b, 0x20, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x43, 0x6c, 0x6f, 0x73, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x0a, 0x0a, 0x0a, 0x0a, 0x03, 0x04, 0x0a, 0x01, 0x12, 0x03, 0x76, 0x08, 0x15, 0x0a, 0x34, 0x0a...
Rust
0
<_>>(), ), base: Some(arena.alloc(sp(Expr::Ident(module_bind)))), }), )); Ok(out.into()) }) } } fn lift_action<'ast>( mut arena: ast::ArenaRef<'_, 'ast, Symbol>, symbols: &mut Symbols, lift: SpannedExpr<'ast, Symbo...
Rust
0
// that supposedly makes the channel open message insane let insane_open_helper = |expected_error_str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| { match nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), LocalFeatures::new(), &message_mutator(open_channel_message.clone())) { Er...
Rust
0
#[pallet::storage] #[pallet::getter(fn staking_info)] pub(super) type StakingInfo<T: Config> = StorageMap<_, Twox64Concat, (u64, T::AccountId), UserStakeInfo<T::AccountId, BalanceOf<T>>>; #[pallet::storage] #[pallet::getter(fn pool_count)] pub(super) type PoolCount<T> = StorageValue<_, u64, ValueQuery>; /// ...
Rust
0
mage.shape[2]-1)) # coords = np.vstack([xx.ravel(),yy.ravel(),zz.ravel()]).T[:, None, :] + V_OFFSETS[None, :, :] # vertices = coords.astype('f') * np.array(self.voxelsize)[None, None, :] # values = self.image[coords[:, :, 0], coords[:, :, 1], coords[:, :, 2]] # # prin...
Python
1
import numpy as np import cv2 import matplotlib.pyplot as plt def hist_match_single_channel(origin, template): """直方图匹配""" origin_shape = origin.shape # 保存图像原始维数 # 扁平化 origin = origin.ravel() template = template.ravel() # 灰度级统计 origin_val, new_origin_idx, origin_val_count = np.unique(orig...
Python
1
#[doc = "Controls the bits in the HcInterruptStatus register and indicates which events will generate a hardware interrupt\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write...
Rust
0
ath_override)?.apply_to(&mut retval, &target_path)?; Ok(retval) } #![warn(clippy::all)] #[macro_use] extern crate log; extern crate clap; use clap::{crate_version, App, Arg}; extern crate flate2; extern crate lz4; extern crate xz2; use std::fs::{File, OpenOptions}; use std::io; use std::io::{Error, ErrorKind}; use...
Rust
0
let sender_addr_raw = deps.api.addr_canonicalize(info.sender.as_str())?; let config: Config = read_config(deps.storage)?; // let mut state: State = read_state(deps.storage)?; let mut staker_info = read_staker_info(deps.storage, &sender_addr_raw)?; // Compute global reward & staker reward // com...
Rust
0
, UTOA10_BUFFER_SIZE, UTOA16_BUFFER_SIZE, }; pub fn utoa10(value: u64) -> String { let mut buffer: [i8; UTOA10_BUFFER_SIZE] = [0; UTOA10_BUFFER_SIZE]; unsafe { kernaux_utoa10(value, buffer.as_mut_ptr()) }; let result = unsafe { CStr::from_ptr(buffer.as_ptr()) }.to_str().unwrap(); String::from(resul...
Rust
0
from src.modules.losses.vqperceptual import DummyLoss
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 4 16:50:56 2020 @author: kadikadi """ # ============================================================================= # The following code will swipe the effect of noise level on SINDy # ============================================================...
Python
1
=entry key=Hex2Str(key) plain=Hex2Str(plain) cipher=Hex2Str(cipher) obj=ciph.new(key, ciph.ECB) ciphertext=obj.encrypt(plain) if (ciphertext!=cipher): die('RC5 failed on entry '+`entry`) for i in ciphertext: print hex(ord(i)), print print ' Completed' #...
Python
1
_size_value_label = QLabel(str(self.circle_size_slider.value()), self) # 初始显示滑块的默认值 self.circle_size_value_label.setStyleSheet("color: #FFFFFF;") bottom_layout.addWidget(self.circle_size_value_label) # 将滑块的 valueChanged 信号连接到更新 QLabel 的函数 self.circle_size_slider.valueChanged.connect(sel...
Python
1
ution.descr != "" assert experiment_execution.id is not None assert experiment_execution.config == experiment_config assert agents_constants.COMMON.AVERAGE_RETURN in experiment_execution.result.plot_metrics assert agents_constants.COMMON.RUNNING_AVERAGE_RETURN in experiment_execution.res...
Python
1
import warnings import pandavro as pdx from optimus.engines.base.io.save import BaseSave from optimus.helpers.logger import logger from optimus.helpers.types import * from optimus.engines.base.io.save import BaseSave class Save(BaseSave): def __init__(self, root: 'DataFrameType'): self.root = root ...
Python
1
length::{convert_length, Units}, SVG_NS, ViewBox, }, }; use crate::common::{ context::Context, svg::{attribute_names::Attribute, attribute_names::NodeExt, length::Length}, }; use crate::common::context::matrix::Matrix; use crate::common::svg; use crate::common::svg::{get_real_node, gradient...
Rust
0
:Path::new(&config_path).join("scripts.toml"); std::fs::write(&path, &s).expect("fail to write scripts config"); println!("scripts config written to {:?}", &path); Ok(Output::new_output("deploy finished!")) } pub fn deposit_request( &mut self, args: DepositRequestArgs, ...
Rust
0
nresolvedReferences df = df.filter(regex='Survived|Age_.*|SibSp|Parch|Fare_.*|Cabin_.*|Embarked_.*|Sex_.*|Pclass_.*') train_np = df.as_matrix() y = train_np[:, 0] x = train_np[:, 1:] return AbuML(x, y, df) def __init__(self, x, y, df, fiter_type=EMLFitType.E_FIT_AUTO): ...
Python
1
import streamlit as st from data_loader import carregar_dados base = carregar_dados() # st.title('Sinteses - Indicadores') # Criar indicadores - PD base_emandamento = base[base["Status"] == "Em andamento"] # Filtro para dados .isin base_fechados = base[base["Status"].isin(["Em andamento", "Finalizado"])] def cri...
Python
1
allocate_shm_file((*keyboard).keymap_size); if keymap_fd < 0i32 { _wlr_log(WLR_ERROR, b"[%s:%d] creating a keymap file for %zu bytes failed\x00" as *const u8 as *const libc::c_char, b"../types/sea...
Rust
0
ering::SeqCst); self.transfer .mem1_buf_idx .store(cur_available, Ordering::SeqCst); stream1_chan1.m1ar.write(|w| unsafe { w.bits(new_target) }); } else { //memory0 is idle, so swap the available buffer with DMA_S2M0AR let cur_mem0 ...
Rust
0