text
string
label_name
string
labels
int64
from datasets import Dataset, DatasetDict, Image, Features, Value from huggingface_hub import create_repo import os import json from tqdm import tqdm import glob from tqdm import tqdm from PIL import Image as PILImage import cv2 def scale_box_coordinates(bbox_2d, x_factor, y_factor): """ 对边界框坐标进行缩放 b...
Python
1
arlark language (i.e. //! Bazel's .bzl files) or the BUILD file dialect (i.e. used to interpret //! Bazel's BUILD file). The BUILD dialect does not allow `def` statements. use std::{mem, slice}; use anyhow::anyhow; use gazebo::prelude::*; use thiserror::Error; use crate::{ codemap::{Span, Spanned}, environme...
Rust
0
let mut headers = Headers::new(); { let hrs = WECHAT.read().unwrap().headers(); let mut cookie = hrs.get::<Cookie>().unwrap().clone(); // cookie.set("wxpluginkey", "1506386162"); headers.set(cookie); headers.set_raw("Host", vec![b"file.web.wechat.com".to_vec()]); ...
Rust
0
import json import matplotlib.pyplot as plt import re def plot_loss_curve(file_path): # 读取文件内容 with open(file_path, 'r') as f: lines = f.readlines() # 使用正则表达式匹配包含'loss'的行并捕获数据 pattern = re.compile(r"\'loss\':\s*(\d+\.\d+),\s*\'grad_norm\':\s*\d+\.\d+,\s*\'learning_rate\':\s*\d+\.\d+,\s*\'epoch...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """Errors and warnings associated with audio recording and playback. """ from ..exceptions import SoundFormatError, DependencyError # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the term...
Python
1
ght_data = 255 if intrplt_right_data < -255: intrplt_right_data = -255 right_data_to_Strng = str(intrplt_right_data) left_data_to_Strng = str(intrplt_left_data) self.left_and_rght_data_to_strng = 'o'+ ' ' + left_data_to_Strng + ' ' + right_data_to_Strng + 'v' print...
Python
1
lags=["dataloss"]) return if not self._fail_on_dataloss_warned: logger.warning( "Got data loss in %s. If you want to process broken " "responses set the setting DOWNLOAD_FAIL_ON_DATALOSS = False" " -- This message w...
Python
1
 ñ\c@sCddlmZddlmZmZdejfdYZdS(i(tunicode_literals(t migrationstmodelst MigrationcBs8eZdgZejdddddejgZRS(uetvu0007_auto_20190413_1101t model_nameuvolcaniceruptio...
Python
1
parse_input(include_str!("input/06.txt")) } fn solve(fish: &[usize], days: usize) -> usize { let mut counts = [0; 9]; for age in fish { counts[*age] += 1; } for _ in 0..days { counts.rotate_left(1); counts[6] += counts[8]; } counts.iter().sum() } fn part1(fish: &[usize]...
Rust
0
PosNormalChannelScalar}; use crate::color::{Bounded, Broadcast, Color, Flatten, FromTuple, HomogeneousColor, Invert, Lerp}; use crate::convert::{FromColor, FromYCbCr}; use crate::encoding::EncodableColor; use crate::rgb::Rgb; use crate::tags::YCbCrTag; #[cfg(feature = "approx")] use approx; use num_traits; use std::fm...
Rust
0
_base_ = [ '../_base_/models/cascade-mask-rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='CascadeRCNN', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indice...
Python
1
m_elements)) } fn get_element(self: &Self, py: Python, idx: usize) -> PyObject { self.get_element(idx).into_vec().into_py_object(py).into_object() } } pub struct WordEmbeddingsGranne { index: granne::Granne<'static, granne::embeddings::SumEmbeddings<'static>>, words: WordDict, } impl Word...
Rust
0
"""Config flow for Kocom Wallpad.""" from __future__ import annotations from typing import Any import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST, CONF_PORT from .const import DOMAIN, DEFAULT_TCP_PORT class KocomConfigFlow(Confi...
Python
1
_clipping", self.lightning_module, pl.LightningModule): rank_zero_warn( "Since DeepSpeed handles gradient clipping internally, the default" " `LightningModule.configure_gradient_clipping` implementation will not actually clip gradients." " The hook will still ...
Python
1
. Only to be used through TI provided API."] #[inline] pub fn reserved1(&mut self) -> _RESERVED1W { _RESERVED1W { w: self } } #[doc = "Bits 8:12 - 12:8\\] Internal. Only to be used through TI provided API."] #[inline] pub fn vddr_trim_sleep_h(&mut self) -> _VDDR_TRIM_SLEEP_HW { _...
Rust
0
# Code generated by Lark OpenAPI. from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type from lark_oapi.core.construct import init class PatchFeedCardRequestBody(object): _types = { "time_sensitive": bool, "user_ids": List[str], } def __init__(self, d=None): ...
Python
1
r) for candidate in candidateMetadaUsages: for referedVar in referedVars: if referedVar == candidate: nextVar = referedVars[referedVars.index(referedVar)+1] print "candidate: 0x%x, candidate end: 0x%x, data numbers: %d" % (candidate, nextVar, (nextVar-candidate)/...
Python
1
for byte in &processor.memory.ram[i..i + self.size as usize] { for x in 0..8 { // Note: The inversion here is necessary, because the highest bit is the first one vec.push((byte & (1 << (7 - x))) != 0); } } vec } } impl Opcode for DRW...
Rust
0
normalization: NameNormalization) -> Self { self.config.name_normalization = name_normalization; self } /// Normalizes all tag and attribute names to lowercase. pub fn lowercase_names(self) -> Self { self.name_normalization(NameNormalization::ToLowercase) } /// Normalizes a...
Rust
0
one, Copy, PartialEq, Eq)] pub enum MeshPrimitive { /// Separate points. Points, /// Separate lines. Lines, /// Line strips. LineStrip, /// Separate triangles. Triangles, /// Triangle strips. TriangleStrip, } impl MeshPrimitive { pub fn assemble(self, indices: u32) -> u32 { ...
Rust
0
::EditOriginalInteractionResponse { application_id: self.application_id, interaction_token, }, }) .await } /// Edits the current user's profile settings. pub async fn edit_profile(&self, map: &JsonMap) -> Result<CurrentUser> { let body = s...
Rust
0
a bit of memory and overall /// performance overhead as lots of metrics are /// tallied up. Nevertheless, it is a useful /// tool for quickly understanding the root of /// a performance problem, and it can be invaluable /// for including in any opened issues. #[cfg(feature = "metrics")] #[allow(clippy::print_stdout)] ...
Rust
0
hash_map { //! A hash map implementation which uses linear probing with Robin //! Hood bucket stealing. pub use super::hashmap::map::*; } pub mod hash_set { //! An implementation of a hash set using the underlying representation of a //! HashMap where the value is (). pub use super::hashmap::s...
Rust
0
let lines = BufReader::new(test_data).lines().map(|l| l.unwrap()); lines.take(n).collect() } fn json_deserialize(lines: &[String], fun: impl Fn(HttpAccessRecord) -> usize) -> usize { lines.iter().enumerate().map(|(no, line)| { match serde_json::from_str::<HttpAccessRecord>(&line) { Err(...
Rust
0
test_id = (select test_id FROM test WHERE test_name = ?) AND length = ? AND word_pool = ? AND mods = ?", params![ &ttc.name, ttc.length, ttc.word_pool, encode_test_mod_bitflag(&ttc.mods), ], |row| row.get(0), ) ...
Rust
0
self.assertIn("Not Found", response.reason) def test_upload_missing_file_error(self): """Missing file should fail with 400 status.""" file_body = { "file1": (None, b"123"), } response = self._upload_files( file_body, session_id="sessionId", file_id="...
Python
1
/// It calls a function `reducer(aggregator: Any, value: Any) => /// updated_aggregator: Any` which combines two values. The /// aggregator is initially the first value seen for a key. Values /// will be passed in arbitrary order. /// /// It emits `(key, aggregator)` tuples downstream at the end of ...
Rust
0
rt!(codec.decode(buf).is_err()); } #[test] fn lines_decoder_max_length_underrun() { const MAX_LENGTH: usize = 6; let mut codec = LinesCodec::new_with_max_length(MAX_LENGTH); let buf = &mut BytesMut::new(); buf.reserve(200); buf.put("line "); assert_eq!(None, codec.decode(buf).unwrap()); b...
Rust
0
C ATOM 54 CD2 TYR A 7 7.210 1.756 9.920 1.00 14.80 C ATOM 55 CE1 TYR A 7 5.480 -0.094 8.796 1.00 13.46 C ATOM 56 CE2 TYR A 7 5.904 1.649 10.416 1.00 14.33 C ATOM 57 CZ TYR A 7 5.047 0.729 9.831 1.00 15.09 ...
Python
1
any] pub target: Option<String>, } impl FilterOptions { /// Construct a package resolver based on the filter options. pub fn make_resolver<'g>( &'g self, pkg_graph: &'g PackageGraph, ) -> Result<impl Fn(&PackageQuery<'g>, PackageLink<'g>) -> bool + 'g> { let omitted_package_ids...
Rust
0
#!/usr/bin/env python3 import argparse import re import sqlite3 import sys from vinetrimmer.utils.AtomicSQL import AtomicSQL """ Add keys to key vault. File should have one KID:KEY per-line. Optionally you can also put `:<title here>` at the end (after `KEY`). """ parser = argparse.ArgumentParser( "Key Vault DB...
Python
1
end: node.text_info().bytes as usize, idx: 0, }) } pub(crate) fn new_empty() -> Chunks<'static> { Chunks(ChunksEnum::Light { text: "" }) } pub(crate) fn new_with_range(node: &Arc<Node>, start_char: usize, end_char: usize) -> Chunks { let start_byte = { ...
Rust
0
from juce_init import START_JUCE_COMPONENT import popsicle as juce class MainContentComponent(juce.Component): frequencySlider = juce.Slider() frequencyLabel = juce.Label() durationSlider = juce.Slider() durationLabel = juce.Label() def __init__(self): juce.Component.__init__(self) ...
Python
1
{}", name), )); } pub fn size(&self) -> usize { self.runtime_class_path.len() } } <gh_stars>0 use mutsolver_core::errors::DictError; use mutsolver_core::Dict; mod fixtures; use fixtures::fixture_dict; macro_rules! vecstr { ($($x:expr),*) => (vec![$($x.to_string()),*]); } #[test] fn te...
Rust
0
#!/usr/bin/python3 def uppercase(str: str) -> None: """ Prints a string in uppercase Args: c (string): the string Notes: If the the argument received is a non-string, the results will be unexpected """ for letter in str: # check for lowercase letters and conve...
Python
1
# -*- coding: utf-8 -*- """The analysis plugins CLI arguments helper.""" import sys from plaso.analysis import manager as analysis_manager from plaso.cli import tools from plaso.cli.helpers import interface from plaso.cli.helpers import manager from plaso.lib import errors class AnalysisPluginsArgumentsHelper(inter...
Python
1
//! It can also initialize each element of a `Arrav<T>` with a given value. //! This may be more efficient than performing allocation and initialization //! in separate steps, especially when initializing a vector of zeros: //! //! ``` //! use arrav::{Arrav, avec}; //! let av = arrav::avec![0; 5]; //! assert_eq!(av, [0...
Rust
0
el_bar_accessible_get_type() -> GType; //========================================================================= // GtkLinkButton //========================================================================= pub fn gtk_link_button_get_type() -> GType; pub fn gtk_link_button_new(uri: *const c_char) ...
Rust
0
len], b"\x07\x03\x84\x00\x00\x01\x00\x01\x00\x00\x00\x00\ \x08quandary\x04test\x00\x00\x01\x00\x01\ \x08quandary\x04test\x00\x00\x01\x00\x01\x00\x00\x0e\x10\x00\x04\ \x7f\x00\x00\x01" ); } #[test] fn writer_detects_qdcount_overflow() { l...
Rust
0
# Generated by Django 1.11.23 on 2019-10-09 14:16 from django.db import migrations, models, transaction def forwards(apps, schema_editor): Column = apps.get_model("seed", "Column") with transaction.atomic(): # Default fields and order are those used before customization was enabled default_g...
Python
1
, angle_yz: float = 0.0, angle_xz: float = 0.0, **kwargs ): """ 4D旋转方法,类似于Manim的rotate方法 """ rotation = rotation_matrix_4d( angle_xw, angle_yw, angle_zw, angle_xy, angle_yz, angle_xz ) new_R = self.R @ rotati...
Python
1
return enhanced_recipe def _enhance_with_genre_materials(self, base_recipe: Dict, genre: str) -> Dict[str, Any]: """장르별 특화 향료로 레시피 강화""" genre_materials = self.genre_specific_materials.get(genre, []) genre_emotions = self.genre_emotions.get(genre, ['neutral']) ...
Python
1
sing a slice object""" global setVal class OldStyle: def __delitem__(self, index): global setVal setVal = index class OldStyleWithLen: def __delitem__(self, index): global setVal setVal = index def __len__(self): re...
Python
1
''' For HMDB51 and UCF101 datasets: Code extracts frames from video at a rate of 25fps and scaling the larger dimension of the frame is scaled to 256 pixels. After extraction of all frames write a "done" file to signify proper completion of frame extraction. Usage: python extract_frames.py video_dir frame_dir ...
Python
1
t = int(input()) for tc in range(1, t+1): n = int(input()) arr = list(map(int, input().split())) arr.sort() found = False min_diff = 999999 for i in range(1, n-1): if arr[i] == arr[i-1]: continue for j in range(i+1, n): if arr[j] == arr[j-1]: ...
Python
1
/// Sets the given *pin* LOW on the shift register at the given *sr_index*. /// If *apply* is `true` the change will be applied immediately. pub fn set_pin_low(&mut self, sr_index: usize, pin: u8, apply: bool) { for (i, sr) in self.shift_registers.iter_mut().enumerate() { if i == sr_in...
Rust
0
tribution( self._modules.targ_policy(batch.next_observations) ).sample() return self._targ_q_func_forwarder.compute_target( batch.next_observations, action.clamp(-1.0, 1.0), reduction="min", ) def inner_predict_best...
Python
1
assert_eq!(solve_part2(&parsed), 3509); } } #![allow(unused_imports)] use super::*; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { # [wasm_bindgen (extends = SvgElement , extends = Element , extends = Node , extends = EventTarget , extends = :: js_sys :: Object , js_name = SVGFESpotLightElement , t...
Rust
0
rChain<Self, U> where Self: Sized, U: Filter, { FilterChain { a: self, b: other } } } struct FilterChain<A, B> { a: A, b: B, } impl<A, B> Filter for FilterChain<A, B> where A: Filter, B: Filter, { fn step(&mut self, sample: f32) -> f32 { self.b.step(self...
Rust
0
in the `stik` atom. const AUDIOBOOK: u8 = 2; /// A media type code stored in the `stik` atom. const WHACKED_BOOKMARK: u8 = 5; /// A media type code stored in the `stik` atom. const MUSIC_VIDEO: u8 = 6; /// A media type code stored in the `stik` atom. const SHORT_FILM: u8 = 9; /// A media type code stored in the `stik`...
Rust
0
"11148817".to_owned(), message_text: "dank cam".to_owned(), is_action: false, sender: TwitchUserBasics { id: "29803735".to_owned(), login: "jun1orrrr".to_owned(), name: "JuN1oRRRR".to_owned() }, ...
Rust
0
y(self, m, Cw): e = np.array(1-Cw) I_u1Betweeny1y2_theory = np.array(Cw*(1-e)) I_u2Betweeny1y2u1_theory = np.array(2*Cw - I_u1Betweeny1y2_theory) if m == 1: output = np.array([I_u1Betweeny1y2_theory, I_u2Betweeny1y2u1_theory]) else: output1 = self.bitChan...
Python
1
6d, 0xa0, 0x3a, 0xdb, 0x5a, 0x77, 0x68, 0xd3, 0x1c, 0xc7, 0xc5, 0xc2, 0xbd, 0x68, 0x28, 0xe1, 0x4a, 0x7d, 0x25, 0xfa, 0x3a, 0x60, ]; fn mk_seed(slot: i64, eta0: &[u8]) -> Vec<u8> { trace!("mk_seed() start slot {}", slot); let mut concat = [0u8; 8 + 32]; NetworkEndian::write_i64(&mut concat, slot); ...
Rust
0
-positive input")] //! #[test_case( 0 => 0 :: "returns 0 for 0")] //! fn abs_tests(x: i8) -> i8 { //! if x > 0 { x } else { -x } //! } //! ``` //! //! Which is equivalent to //! //! ``` //! #[test_case( 2, 2 :: "returns given number for positive input")] //! #[test_case(-2, 2 :: "returns opposite number for non-posi...
Rust
0
import unittest import main class TestStringMethods(unittest.TestCase): def test_hiraganafy(self): test_cases = [ {'in': 'カタカナ', 'out': 'かたかな'}, {'in': '漢字', 'out': 'かんじ'}, {'in': 'ひらがな', 'out': 'ひらがな'}, {'in': '哺乳瓶', 'out': 'ほにゅうびん'}, {'in': '長...
Python
1
able(..) | ty::PredicateAtom::ConstEquate(..) | ty::PredicateAtom::TypeWellFormedFromEnv(..) => false, } }) } /// Returns `Some(_)` if this method makes the containing trait not object safe. fn object_safety_violation_for_method( tcx: TyCtxt<'_>, trait_def_id: DefId, met...
Rust
0
"""Define the main controller.""" from typing import List from models.deck import Deck from models.player import Player class Controller: """Main controller.""" def __init__(self, deck: Deck, view, checker_strategy): """Has a deck, a list of players and a view.""" # models self.play...
Python
1
# https://leetcode.com/problems/set-matrix-zeroes/ class Solution: def setZeroes(self, matrix: list[list[int]]) -> None: # In-place solution # Use the first row and col to mark what needs to be zeroed out later rows = len(matrix) cols = len(matrix[0]) row_zero_flag = False ...
Python
1
lang = lang.partition("-")[0] for ch in text.extract_iter(group, "<li ", "</li>"): path = text.extr(ch, 'href="', '"') chap = text.extr(ch, 'data-number="', '"') name = text.unescape(text.extr(ch, 'class="name">', "<")) chapter, sep, minor = chap.partition("....
Python
1
# BSD 3-Clause License # # Copyright 2022 Hewlett Packard Enterprise Development LP # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this li...
Python
1
ize }, 0usize, concat!( "Offset of field: ", stringify!(AlterDatabaseSetStmt), "::", stringify!(type_) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<AlterDatabaseSetStmt>())).dbname as *const _ as usize }, 8usize, ...
Rust
0
import numpy as np def jaccard_similarity(set_a, set_b): inter = len(set_a.intersection(set_b)) union = len(set_a.union(set_b)) return inter / union if union > 0 else 0.0 def precision_at_k(pred_draw, true_draw, k=20): set_pred = set(pred_draw[:k]) set_true = set(true_draw) return len(set_pred...
Python
1
proj_rgb = None output_all = { "proj": proj, "voxels": voxels, "tr_pc": tr_pc, "voxels_rgb": voxels_rgb, "proj_rgb": proj_rgb, "drc_probs": drc_probs, } output = output_all['proj'] voxels = output_all['voxels'] tr_pc = output_all['tr_pc'] return...
Python
1
nsure!(&$purchaser != account, Error::<T>::DuplicatedBid); let _ = T::MultiCurrency::unreserve($auction.currency_id, account, $auction_bid.last_bid_price); } T::MultiCurrency::reserve($auction.currency_id, &$purchaser, $price)?; let mut auction_bid = $auction_bid; auction_bid.last_bid_price = $price; auct...
Rust
0
&x; let pub_z = ProjectivePoint::from(gen_m.clone()) * &x; let proof = Proof::new_p256_sha256( gen_g, pub_h.to_affine().unwrap(), gen_m, pub_z.to_affine().unwrap(), &x, ) .expect("dleq proof"); assert!(proof.verify().is...
Rust
0
from pathlib import Path from typing import Any, Optional, Union from typing_extensions import override from ..model import YandexResponse from ..utils import read_file from .base import BaseSearchEngine class Yandex(BaseSearchEngine[YandexResponse]): """API client for the Yandex reverse image search engine. ...
Python
1
from hangman_art import stages from init import init_game from randomly_word import randomly_chosen_word as chosen_word_func from message_printer import line_printer is_game_finished = False lives = 6 display = [] # greeting init_game() # randomly choose a word chosen_word = chosen_word_func() # display for each lett...
Python
1
) np.save(f,spk_total_binary) # def plot_raster_sort(raster,sort_per_minute=True): # if sort_per_minute: # pop_FR=raster.sum(axis=0) # desc_FR_neu=np.argsort(raster.sum(axis=1)) # raster=raster[desc_FR_neu,:] # f=np.argwhere(raster!=0) # neuro=f[:,0] # spike=f[:,1] # return ne...
Python
1
impl ParseCsv<8> for Definition { const HEADER_LINE: Option<&'static str> = Some(HEADER_LINE); const FOOTER_LINE: Option<&'static str> = None; type Error = ParseError; fn parse_line(line: [String; 8]) -> Result<Self, Self::Error> { let [id, r, g, b, kind, coastal, terrain, continent] = line; Ok(Def...
Rust
0
in parallel //! with different bit rates should see different clock //! frequencies. use capsules::virtual_spi::MuxSpiMaster; use components::spi::SpiComponent; use core::cell::Cell; use kernel::component::Component; use kernel::debug; use kernel::hil::spi::{self, SpiMasterDevice}; use kernel::ErrorCode; #[allow(unu...
Rust
0
y_state == (). if (global_step.numpy() % real_collect_interval == 0 and global_step.numpy() >= delta_r_warmup): real_time_step, policy_state = real_collect_driver.run( time_step=real_time_step, policy_state=policy_state, ) for _ in range(train_steps_per_ite...
Python
1
nt)''' def check_connect(adj): dvec = np.sum(adj, axis=1) D = [1/np.sqrt(d) if d != 0 else 0 for d in dvec] D = np.diag(D) #print(D) Nadj = np.matmul(np.matmul(D, adj), D) #alleigs = spla.eigs(Nadj, k = 9, which = 'LR', return_eigenvectors=False) alleigs = la.eigh(Nadj, eigvals_only=True, su...
Python
1
Self::Target { &self.0 } } #[doc = "Field `CMPMATCNT` writer - Compare Match Count\nWhen the specified A/D channel analog conversion result matches the compare condition defined by CMPCOND bit, the internal match counter will increase 1. When the internal counter reaches the value to (CMPMATCNT +1), the CMP...
Rust
0
2rust/#read--modify--write-api).\n\nFor information about available fields see [hstdmacontrol6](hstdmacontrol6) module"] pub type HSTDMACONTROL6 = crate::Reg<u32, _HSTDMACONTROL6>; #[allow(missing_docs)] #[doc(hidden)] pub struct _HSTDMACONTROL6; #[doc = "`read()` method returns [hstdmacontrol6::R](hstdmacontrol6::R) r...
Rust
0
""" MEMFORMAT KODE """ print("MEMFORMAT KODE") """ PENJELASAN: jika proses linting menghasilkan pesan dengan menunjukkan baris dan kode yang mengalami kesalahan, proses memformat kode akan memberikan pesan berupa kode yang telah diperbaiki. Ini artinya Anda tidak perlu mengubah kode secara manual """ class Kalkulato...
Python
1
ers=dataloader_num_workers, dataloader_prefetch_factor=cfg.train.dataloader_prefetch_factor, tf32=use_tf32, # remove this if not using Ampere GPUs (e.g., A100) torch_compile=cfg.train.torch_compile, ddp_find_unused_parameters=cfg.train.ddp_find_unused_parameters, remove_unused_c...
Python
1
println!( concat!( "\n# aquatic load test report\n\n", "Test ran for {} seconds.\n", "Average responses per second: {:.2}\n\nConfig: {:#?}\n" ), time_elapsed.as_secs(), report_avg, ...
Rust
0
if !self.render_redirect_pages { self.shared.all.borrow_mut().append(full_path(self, &item), &item_type); } // If the item is a macro, redirect from the old macro URL (with !) // to the new one (without). if item_type == ItemType::Macro { ...
Rust
0
); } Action::BlockApplierApplyProtocolRunnerApplyRetry(content) => { slog::warn!(log, "Block application failed! Retrying..."; "error" => format!("{:?}", content.reason), "block_hash" => format!("{:?}", content.block_hash)); } A...
Rust
0
subgoal_pred = model_out["subgoal"].squeeze(2) subgoal_gt = gt_dict["subgoals_completed"] subgoal_loss = F.mse_loss(subgoal_pred, subgoal_gt, reduction="none") subgoal_loss = subgoal_loss.view(-1) * pad_mask.float() subgoal_loss = subgoal_loss.mean() los...
Python
1
, sig, block_number: None, addresses: None }; let response = get_enc_state_keys(enclave.geteid(), request, epoch_state.nonce, &[]).unwrap(); enclave.destroy(); } } <filename>src/syscon/system_cfg1.rs #[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write...
Rust
0
import os import re import json from random import choice from nonebot import get_bot from nonebot.params import ArgPlainText from nonebot.adapters.onebot.v11 import ( Message, MessageEvent, MessageSegment, GroupMessageEvent, ) from nonebot.adapters.onebot.v11.helpers import Cooldown from ATRI.service...
Python
1
pub enum Block{ AIR = 0, SOLID = 1, DESTRUCTABLE = 2 } impl Block{ pub fn from(val: usize) -> Block{ match val{ 0 => Block::AIR, 1 => Block::SOLID, 2 => Block::DESTRUCTABLE, _ => Block::AIR } } } use super::graphics::Texture; pub struct Room{ pub images: Vec<Texture>,...
Rust
0
ist = L._tree_cutlist # else: # # Can't force hdbscan to always output a given number of clusters # if algo == 1: # s1, s2 = 2, int(X.shape[0]) # # while 1 < s1 <= s2: # s = int((s1+s2)/2) # h = hdbscan.HDBSCAN(min_cluster_size=s, min_samp...
Python
1
= torch.cat([sensors, pn_feat, sensors_goal, pn_feat_goal], dim=-1) return dexrep_feat class SharedDexrepV2GSensor(SharedDexrep2GSensor): def __init__(self, args): super(SharedDexrepV2GSensor, self).__init__(args) self.Sensor.sensot_type = "dexrep_VtoGoal" ...
Python
1
it into a relevant collection. // This is one of the more powerful methods in the standard library, // used in a variety of contexts. // Vec<T> : A contiguous growable array type, written as Vec<T>, short for 'vector'. let token : Vec<&str> = my_string.split("*").collect(); println!("{:?}", token)...
Rust
0
Option<Statistics>, ) -> Result<(), Error> { if let Some(stats) = statistics { return gap_mode_statistics(graph, generators, stats); } // Early exit if full quotient is descriptive. let full_orbits = generate_orbits(&mut generators); if check_class(graph, full_orbits.clone())? { pr...
Rust
0
(6, 25); let bsz_minmax_h = (10, sy + 2); // wipe canvas canvas.fill_with(*background); for (d, l) in layers_desc.iter().zip(layers.iter_mut()) { // spawn a new building on this layer // don't spawn if not moving on this tick && spawn decision let th...
Rust
0
, i, j) = (var(), var(), var(), var(), var(), var(), var(), var(), var(), var()); all![ unify(a, 1), unify(b, 1), unify(c, 1), unify(d, 1), unify(e, 1), unify(f, 1), unify(g, 1), ...
Rust
0
# this code is auto generated by the expr_codegen # https://github.com/wukan1986/expr_codegen # 此段代码由 expr_codegen 自动生成,欢迎提交 issue 或 pull request import numpy as np # noqa import pandas as pd # noqa import polars as pl # noqa import polars.selectors as cs # noqa from loguru import logger # noqa # ===============...
Python
1
import plotly.express as px from plotly import colors from utils.utils_config import BG_TRANSPARENT, HOVERLABEL_TEMPLATE def create_bubble(df, switcher): step_x = 5000 step_y = 1 max_x_range = [df['GDP'].min() - step_x, df['GDP'].max() + step_x] max_y_range = [df['Prevalence'].min() - step_y, df['P...
Python
1
import requests from bs4 import BeautifulSoup def extract_linkedin_profile(url): try: # Send an HTTP request to the LinkedIn profile URL response = requests.get(url) response.raise_for_status() # Raise an HTTPError for bad responses # Parse the HTML content using BeautifulSoup ...
Python
1
.update(&member.certificate).unwrap(); let signature = member.sign(&vec![2, 4, 5]); verifier.verify(&signature, &vec![2, 4, 5]).unwrap(); ///////////////////////// match verifier.verify(&signature, &vec![2, 4, 4]) { Ok(_) => { assert!(false); } Err(_) => {} } ...
Rust
0
import streamlit as st import numpy as np from joblib import load # Load the model model = load('decision_tree.pkl') # Define the prediction function def passenger_survival_predictor(pclass, sex, age, sibsp, parch, fare, embark_town_Queenstown, embark_town_Southampton): result = model.predict([[pclass, sex, age, ...
Python
1
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from sqlframe.base.column import Column from narwhals._spark_like.expr import SparkLikeExpr class SparkLikeExprStructNamespace: def __init__(self, expr: SparkLikeExpr) -> None: self._compliant_expr = expr ...
Python
1
""" 使用有限状态机算法 通过已经创建的事件和状态 对订单状态进行自动的调度 """ # pylint: disable=arguments-differ from typing import NoReturn from ...core.tools import web from ...core.algorithm import fsm from . import events from . import status from . import settings # 状态转移表 _TransferTable = ( (status.Created, events.Confirm, status.Confirmed)...
Python
1
import os if_exist = os.path.exists("info3.txt") if if_exist: os.rename("info3.txt","newinfochecker.txt") print("Its Done") else: print("File not found")
Python
1
(MatchToken::Data(len, constraint), ScriptBit::PushData(_, data) | ScriptBit::Push(data)) => match constraint { DataLengthConstraints::Equals => Ok(&data.len() == len), DataLengthConstraints::GreaterThan => Ok(&data.len() > len), DataLengthCons...
Rust
0
//! whatever remaining work there may be. use actix::prelude::*; use actix::{Actor, Context}; use failure::Error; use settings::RitaCommonSettings; use std::collections::HashMap; use std::net::{IpAddr, Ipv6Addr, SocketAddr, SocketAddrV6, UdpSocket}; use rita_common::rita_loop::Tick; use KI; use SETTING; mod messag...
Rust
0
mensions(&self) -> Vec<usize> { match &self.get_field_type().value { Some(x) => match x { wonnx::onnx::TypeProto_oneof_value::tensor_type(t) => t.get_shape().shape_dimensions(), wonnx::onnx::TypeProto_oneof_value::sequence_type(_) => todo!(), wonnx::onnx::TypeProto_oneof_value::map_type(_) => todo!(), ...
Rust
0