text
string
label_name
string
labels
int64
ts[input.len() - 1][input[0].len() - 1] } fn build_bigger_map(input: &[Vec<i32>]) -> Vec<Vec<i32>> { let mut new_grid = Vec::new(); for i in 0..5 { for y in 0..input.len() { let mut y_vec = Vec::new(); for j in 0..5 { for x in 0..input[0].len() { ...
Rust
0
pretrained=None, decode_head=dict( type='UPerHead', in_channels=[96, 192, 384, 768], in_index=[0, 1, 2, 3], pool_scales=(1, 2, 3, 6), channels=512, dropout_ratio=0.1, num_classes=150, ...
Python
1
0x00400000, 0x004D2D10 => read_file(*const u8, u32, u32, *const u8, u32, @ecx u32, @eax *mut usize) -> *mut u8; 0x0049C9F0 => get_region(@edi u32, @ecx u32) -> u32; 0x004390A0 => change_ai_region_state(@esi *mut c_void, @ebx u32); 0x00474810 => prepare_issue_order(@edx *mut Unit, @ecx u32, u32,...
Rust
0
from heapq import heappop, heappush from collections import defaultdict intersections, streets = tuple(map(int, input().split())) start, goal, delay, number_visited_by_george = tuple(map(int, input().split())) order_visited_by_george = list(map(int, input().split())) transitions = defaultdict(lambda: {}) for _ in ran...
Python
1
"""Integration tests Higher-level tests integrating with 3rd party modules using iodiomatic backoff patterns. """ import backoff import requests from requests import HTTPError import responses @responses.activate def test_on_predicate_runtime(monkeypatch): log = [] def sleep(seconds): log.append...
Python
1
s. /// Returns the server's address. pub async fn run_echo_server(&mut self) -> EndpointAddress { self.run_echo_server_with_tap(|_, _, _| {}).await } /// Runs a simple UDP server that echos back payloads. /// The provided function is invoked for each received payload. /// Returns the se...
Rust
0
# Evaluate Expression to True Boolean Parenthesization Recursive # https://practice.geeksforgeeks.org/problems/boolean-parenthesization5610/1 # https://www.interviewbit.com/problems/evaluate-expression-to-true/ st = "T^F|F" s = list(st) dp = {} def solve(s, i, j, isTrue): if(i > j): return 1 if(...
Python
1
]) all_flag.appendChild(_helpers.create_xml_dom_element( doc, 'usage', usage_doc)) # Get list of key flags for the main module. key_flags = self.get_key_flags_for_module(sys.argv[0]) # Sort flags by declaring module name and next by flag name. flags_by_module = self.flags_by_module_dict() ...
Python
1
A2CNT_L", REG_DMA2CNT_H => "REG_DMA2CNT_H", REG_DMA3SAD => "REG_DMA3SAD", REG_DMA3DAD => "REG_DMA3DAD", REG_DMA3CNT_L => "REG_DMA3CNT_L", REG_DMA3CNT_H => "REG_DMA3CNT_H", REG_TM0CNT_L => "REG_TM0CNT_L", REG_TM0CNT_H => "REG_TM0CNT_H", REG_TM1CNT_L => "REG...
Rust
0
import logging from celery import Celery import subprocess from dotenv import dotenv_values import time logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) config = dotenv_values(".env") sqs_queue_url = config['sqs_queue_url'] aws_access_key = config['aws_access_key'] aws_secret_key = confi...
Python
1
*const _, trap_frame ), #[cfg(target_pointer_width = "32")] cause => panic!( "Unhandled exception! mcause: {:?}, mepc: {:08x?}, mtval: {:08x?}, mstatus: {:08x?}, trap frame: {:x?}", cause, mepc::read(), mtval::read(), mstat...
Rust
0
""" model.py 定义了 PSA算法 (Learning Pixel-level Semantic Affinity with Image-level Supervision) 的网络架构 @Time : 2025/05/20 @Author : JackWang @File : model.py @IDE : VsCode @Copyright Copyright Shihong Wang (c) 2025 with GNU Public License V3.0 """ # Standard Library # Third-Party Library ...
Python
1
ref: Parents, pub exp_ref: Parents, pub bod_ref: Parents, pub copy: Option<NonNull<Let>>, pub var: Var, pub parents: Option<NonNull<Parents>>, } #[repr(C)] pub struct Ref { pub nam: Name, pub rec: bool, pub exp: Cid, pub ast: Cid, pub parents: Option<NonNull<Parents>>, } #[repr(C)] pub struct Typ ...
Rust
0
} <gh_stars>0 // Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license //! Read static string using the XYZ file format, and create the corresponding //! system. use crate::{Molecule, Particle, System, UnitCell}; /// Read the `content` string, assuming XYZ format, and c...
Rust
0
[problem_id]['response'] if verify_response(response): # logging.info(f"Valid response found for {pid}.") skip_pids.append(problem_id) if len(skip_pids) > 0: logging.info( f"Found existing results file with {len(skip_pids)} problems with v...
Python
1
{ pub fn iirdecim_cccf_execute_block( _q: iirdecim_cccf, _x: *mut liquid_float_complex, _n: ::std::os::raw::c_uint, _y: *mut liquid_float_complex, ); } extern "C" { pub fn iirdecim_cccf_groupdelay(_q: iirdecim_cccf, _fc: f32) -> f32; } #[repr(C)] #[derive(Debug, Copy, Clone)...
Rust
0
3::new(0.0, 0.0, 0.0))) .set_field_of_view(20.0) .set_shutter_open_time(0.0) .set_shutter_close_time(1.0); let mut scene = render::Scene::new() .set_camera(camera) .add_object(Object::new(objects::Sphere::new(Vec3::new(0.0, 1.0, -600.5), 600.0...
Rust
0
overlapping(DIGIT_TABLE.get_unchecked(c0 as usize), result.offset(-2), 2); ptr::copy_nonoverlapping(DIGIT_TABLE.get_unchecked(c1 as usize), result.offset(-4), 2); result = result.offset(-4); } if output >= 100 { let c = ((output % 100) << 1) as u32; output /= 100; ptr::co...
Rust
0
application")] Deploy, } #[derive(Debug, Clone, StructOpt)] pub struct CleanCmd { #[structopt(flatten)] pub loudness: LoudnessOpts, #[structopt( name = "cargo-manifest-path", long = "manifest-path", parse(from_os_str), default_value = "./Cargo.toml", help = "Pat...
Rust
0
let sensible_xfer_rate: f64 = calc_sensible_heat_xfer_rate(stability_factors_v_h, sensible_heat_xfer_co, adjusted_wind_speed, air_temperature); let latent_xfer_rate: f64 = calc_latent_heat_xfer_rate(stability_factors_v_h, latent_heat_xfer_co, adjusted_wind_speed, vapor_pressure); let condensatio...
Rust
0
from django.urls import path, re_path from .views import chooser, editor app_name = "wagtailnews" urlpatterns = [ re_path(r"^$", chooser.choose, name="choose"), re_path(r"^search/$", chooser.search, name="search"), re_path(r"^(?P<pk>\d+)/$", chooser.NewsItemIndexView.as_view(), name="index"), re_path(...
Python
1
from django.contrib import admin from import_export import resources from import_export.admin import ImportExportModelAdmin from .models import ModelWrfStilt, Receptor, Region admin.site.site_header = "MODEL-Admin" admin.site.site_title = "MODEL-Admin" admin.site.index_title = "MODEL-Admin" class ReceptorResource(r...
Python
1
# Main Class class Members: def __init__(self, n, p): self.name = n self.permission = p def show_info(self): return f"Your Name Is {self.name} And You Are {self.permission}" # Create Admin Class Here class Admins(Members): pass # Create Moderators Class Here class Moderators(Admins): ...
Python
1
ketOptionsRequest, ) -> Result<(), aws_smithy_http::operation::SerializationError> { #[allow(unused_mut)] let mut scope_947 = writer.prefix("MarketType"); if let Some(var_948) = &input.market_type { scope_947.string(var_948.as_str()); } #[allow(unused_mut)] let mut scope_949 = writer.pre...
Rust
0
<'h> { fn default() -> VkObjectTablePipelineEntryNVX<'h> { VkObjectTablePipelineEntryNVX::new() } } #[cfg(feature = "VK_NVX_device_generated_commands")] unsafe impl<'h> Struct for VkObjectTablePipelineEntryNVX<'h> {} #[cfg(feature = "VK_NVX_device_generated_commands")] #[cfg(test)] #[test] fn test_struct_size_v...
Rust
0
_API_GET_AUTHENTICATION_CODE, req, opt) } pub fn get_authentication_code(&self, req: &super::auth::GetAuthenticationCodeRequest) -> ::grpcio::Result<super::auth::GetAuthenticationCodeResponse> { self.get_authentication_code_opt(req, ::grpcio::CallOption::default()) } pub fn get_authentication_...
Rust
0
)): if np.issubdtype(x.dtype, np.complexfloating) or self.ignore_inf_sign: pinf_x = np.isinf(x) pinf_y = np.isinf(y) minf_x = np.isinf(x) minf_y = np.isinf(y) else: pinf_x = np.isposinf(x) pinf_y = np...
Python
1
import fire import torch from transformers import AutoModelForCausalLM def compare_model_layers(model1, model2, layers_to_check): for layer in layers_to_check: for param1, param2 in zip( model1.model.layers[layer].parameters(), model2.model.layers[layer].parameters(), ): ...
Python
1
_linear(val.r), srgb_to_linear(val.g), srgb_to_linear(val.b)) } }<reponame>DixydL/ma_rgl<filename>src/lib.rs<gh_stars>1-10 pub mod matrix { use std::ops::Mul; #[derive(Debug)] pub struct Matrix { mat1 :[f32;4], mat2 :[f32;4], mat3 :[f32;4], mat4 :[f32;4], mat5 :[f...
Rust
0
= XMVector3Normalize(Axis); return XMMatrixRotationNormal(Normal, Angle); } /// Builds a rotation matrix from a quaternion. /// /// ## Parameters /// /// `Quaternion` Quaternion defining the rotation. /// /// ## Return value /// /// Returns the rotation matrix. /// /// ## Reference /// /// <https://docs.microsoft....
Rust
0
warn!("Unable to get message of journald kernel record"); return RecordStatus::BadLine; } }; RecordStatus::Line(format!("{} {} kernel: {}", timestamp, hostname, message)) } } impl<'a> Source<'a> for JournaldSource { fn drain(&mut self...
Rust
0
def send(key, client): while True: message = input() client.send_message(message, key)
Python
1
E_FILE, debug, &mut launch_token, &mut launch_token_updated, &mut misc_attr, ) } static mut ENCLAVE: SgxEnclave = unsafe { std::mem::transmute([1u8; std::mem::size_of::<SgxEnclave>()]) }; static mut TARGET: usize = 0; fn main() -> std::io::Result<()> { #[cfg(not(feature = "...
Rust
0
# My name is Oluwatimilehin Amoo from CSIT 111 CLW # I wrote this program to help a user know what generation they fall under. # Welcome message print ("Welcome to GenAge.") print ("I'll be telling you what generation you belong to based on your birth years.") # This part of the code is to accurately decide what gene...
Python
1
serde(default, skip_serializing)] #[cfg_attr(not(debug_assertions), serde(skip_deserializing))] pub endpoints: Endpoints, } impl<T> RuntimeSettings for Settings<T> where T: Clone, { type Config = T; fn agent(&self) -> &ModuleSpec<T> { &self.agent } fn agent_mut(&mut self) -> &mut ...
Rust
0
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
Python
1
from TwitterAPI import TwitterAPI, TwitterOAuth, TwitterRequestError, TwitterConnectionError, HydrateType import json TWEET_ID = '1360029234773770240' EXPANSIONS = 'author_id,referenced_tweets.id,referenced_tweets.id.author_id,in_reply_to_user_id,attachments.media_keys,attachments.poll_ids,geo.place_id,entities.menti...
Python
1
pub enum ImportType { #[structopt(name = "factoid")] Factoid, #[structopt(name = "hresult")] HResult, #[structopt(name = "ntresult")] NtResult, #[structopt(name = "win32")] Win32, } #[derive(Deserialize)] pub struct Config { #[serde(rename = "connection")] pub nestor: nestor::co...
Rust
0
r| r.iter().map(|&e| e))); match res { Err(PgDbError(ref err)) if err.message[].contains("Invalid column count") => {} Err(err) => panic!("unexpected error {}", err), _ => panic!("Expected error"), } let data: &[&[&ToSql]] = &[&[&0i32, &"Steven".to_string()], &[&1i32, &"Steven".to_s...
Rust
0
sort. impl From<&str> for AtomicTerm { fn from(item: &str) -> Self { AtomicTerm::gen_raw_variable_term(item.to_string(), vec![]) } } impl From<usize> for AtomicTerm { fn from(item: usize) -> Self { let atom_enum = AtomEnum::Int(num::BigInt::from(item)); AtomicTerm::gen_atom_term(ato...
Rust
0
status = "Ready to Reprocess" obj_source_node.file_name = file_name.strip() if isinstance(file_name, str) else file_name obj_source_node.status = status obj_source_node.retry_condition = retry_condition obj_source_node.is_cancelled = False if retry_condition == DELETE_ENTITIES_AND_START_FROM_BEG...
Python
1
train_mae, train_r2, val_mae, val_r2): """Simplified training analysis with focus on convergence and overfitting""" best_val_epoch = np.argmin(val_loss) + 1 min_val_loss = val_loss[best_val_epoch - 1] overfit_ratio = (val_loss[-1] - min_val_loss) / min_...
Python
1
no_schema_provided(test_db) -> None: with pytest.raises( ValueError, match="Cannot read DataFrame with infer_schema=False and schema=None, please provide a schema or set infer_schema=True", ): daft.read_sql(f"SELECT * FROM {TEST_TABLE_NAME}", test_db, infer_schema=False) @pytest.mark.i...
Python
1
请先删除子菜单") # 删除菜单 self.db.delete(menu) self.db.commit() logger.info(f"菜单 {menu_id} 删除成功") return True return self._safe_query(_query, f"删除菜单失败: 菜单ID {menu_id}", False) def get_menu_tree(self, parent_id: Option...
Python
1
p in applications: benefit_type = app.benefit.benefit_type if benefit_type not in benefit_types: benefit_types[benefit_type] = { 'count': 0, 'total_benefit': 0, 'total_original': 0 } ...
Python
1
a = 1 b = 2 c = 3 if a > b: print("a is greater than b") if b != c: print("but b is not equal to c") else: print("b is equal to c") else: print("a is less than b")
Python
1
# -------------------------------------------------------- # Fast/er R-CNN # Licensed under The MIT License [see LICENSE for details] # -------------------------------------------------------- """ Transform images for compatibility with models trained with https://github.com/facebook/fb.resnet.torch. Usage in model p...
Python
1
order=1, ), FixPlanEnableStep( data=EnableData( service="esm-apps", source_packages=["pkg3", "pkg4"], ...
Python
1
from odoo import Command from odoo.addons.hr_expense.tests.common import TestExpenseCommon from odoo.tests import tagged, HttpCase @tagged('-at_install', 'post_install') class TestUi(TestExpenseCommon, HttpCase): browser_size = "1920,1080" def test_show_expense_receipt_on_expense_line_click(self): ex...
Python
1
in ['ID', 'ANNEE_ASSURANCE']] # Remplir les NaN des colonnes non numériques avec une valeur par défaut (-999) X_test[fill_cols] = X_test[fill_cols].fillna(-999) # Suppression des colonnes inutiles # X_test_model = encoder.transform(X_test.drop(['ID'], axis=1)) X_test_model = X_test.drop(['ID'], axis=1) X_test_mo...
Python
1
from django.contrib import admin from .models import ProductCountdown # Register your models here. class ProductCountdownAdmin(admin.ModelAdmin): list_display = ('name', 'target_date', 'is_active', 'is_countdown_finished') list_filter = ('is_active', 'target_date') search_fields = ('name', 'description')...
Python
1
import whois from discord_webhook import DiscordWebhook import schedule import time from datetime import datetime, timedelta import os # Configuration DOMAIN = os.environ.get('DOMAIN', '') # Get domain from environment variable, default to empty string WEBHOOK_URL = os.environ.get('WEBHOOK_URL', '') # Get webhook UR...
Python
1
(Chris): Count is not the total number of bytes, but rather the number of values // (the length of which is specified by the field type) let count = usizeify(take_bytes(ifd_bytes, &mut ifd_advance, 4), byte_order); let byte_count = if let EntryType::Short = field_type_enum { count *...
Rust
0
Clone, Copy, Debug, PartialEq)] pub enum LegProvisionOptionExerciseBusinessDayConvention { /// Not applicable #[serde(rename = "0")] NotApplicable, /// None (current day) #[serde(rename = "1")] None, /// Following day #[serde(rename = "2")] FollowingDay, /// Floating rate note #[serde(rename = "3")] Floati...
Rust
0
false; } !(3..=(n/2)).filter(|x| x % 2 != 0).any(|x| n % x == 0) } // pub fn nth(n: u128) -> u128 { // (0..).filter(|x| is_prime(x)) // .take(n as usize + 1) // .last().unwrap() // } fn prime_number_generator_a(max: u128) -> Vec<u128> { let mut primes = vec![2]; for n in 3..max { ...
Rust
0
, shrink_manager) = Fbas::shrunken(fbas, fbas.satisfiable_nodes()); debug!( "Shrank to an FBAS of size {}.", fbas_shrunken.number_of_nodes() ); Analysis { fbas_original: fbas.clone(), fbas_shrunken: RefCell::new(fbas_shrunken), shrink_m...
Rust
0
_order, zhiyuan_mode) if (select_result == 'return'): self.lock_home() return 'return' # 进入战斗 F = TZ.goto_fight() During = F.get_during() F.set_auto(1, screen=self.last_scr...
Python
1
# Problem link - https://www.geeksforgeeks.org/function-to-find-number-of-customers-who-could-not-get-a-computer/ def get_no_computer_customers(num_computers, customers): """ Overall time complexity is O(n) and space is O(1). """ # store the number of computers available. original_num_of_comp...
Python
1
merfd_create(2)`]. /// /// [`timerfd_create(2)`]: http://man7.org/linux/man-pages/man2/timerfd_create.2.html pub struct TimerFd(RawFd); fn neg_is_err(i: libc::c_int) -> IoResult<libc::c_int> { if i >= 0 { Ok(i) } else { Err(std::io::Error::last_os_error()) } } impl TimerFd { /// Create...
Rust
0
new().expect("Pipe creation not to fail"); let (input_tx, input_rx) = channel(); let renderer = new_wezterm_terminfo_renderer(); let tw_term = TermWizTerminal { render_tx: TermWizTerminalRenderTty { render_tx: BufWriter::new(render_pipe.write), screen_size: ScreenSize { ...
Rust
0
Iterator<Item = T>, D: Iterator<Item = u32>, { type Item = Option<T>; fn next(&mut self) -> Option<Self::Item> { match self.def_levels.next() { Some(def) => { if def == self.max_def_level { Some(self.values.next()) } else { ...
Rust
0
s { proj: proj.into(), view: view.into(), } }); for sky in (&skybox).join() { let mesh = self.mesh.as_ref().unwrap(); //FIXME: it is probably not necessary to push the mesh to the GPU every frame. Loading /...
Rust
0
me, condition: condition.clone(), duration, }; change = change.apply(&log)?; } _ => bail!(GameError::BuggyProgram("Ugh".to_string())), } change } }; if in_combat { change = change.apply_creature(creature.id(), |...
Rust
0
# Copyright (c) 2010-2022 openpyxl from openpyxl.worksheet.header_footer import HeaderFooter from openpyxl.descriptors import ( Bool, Integer, Set, Typed, Sequence ) from openpyxl.descriptors.excel import Guid from openpyxl.descriptors.serialisable import Serialisable from openpyxl.worksheet.page ...
Python
1
#08_ import pygame from pygame.locals import * from sys import exit import random screen_width = 600 screen_height = 400 spoon_x = 300 spoon_y = screen_height - 100 raspberry_x = random.randint(10, screen_width) raspberry_y = 0 pygame.init() screen = pygame.display.set_mode((screen_width, screen_height)) pygame.d...
Python
1
# Copyright 2009-2017 Ram Rachum. # This program is distributed under the MIT license. '''Defines various tools related to temporary files.''' from __future__ import generator_stop import tempfile import shutil import pathlib from python_toolbox import context_management @context_management.ContextManagerType def...
Python
1
""" 生成结论信息。 参数: result_options: 数据来源 options 返回: str: 生成的结论信息。 """ # 读取生产环境和回放环境的 CSV 文件 producer_parquet_file_path = result_options.get('producer_parquet_file_path') playback_parquet_file_path = result_options.get('playback_parquet_file_path') alignment_parquet_fi...
Python
1
import requests import time import sqlite3 import os TWSE_URL = 'http://www.twse.com.tw/exchangeReport/STOCK_DAY?response=json' CSV_FILE_NAME = "stockThisMonth.csv" def get_web_content(stock_id, current_date): resp = requests.get(TWSE_URL + '&date=' + current_date + '&stockNo=' + stock_id) if resp.status_code...
Python
1
KEY>", ]) .unwrap(); let decode_matches = matches.subcommand_matches("decode").unwrap(); let (result, _, _) = decode_token(&decode_matches); assert!(result.is_ok()); } #[test] fn decodes_a_token_without_a_typ() { let matches = config_options() ...
Rust
0
api .public(ApiKind::Explorer) .query(&json!({ "tx_body": tx })) .post("v1/transactions") .await .unwrap(); assert_eq!(tx.object_hash(), tx_info.tx_hash); } #[tokio::test] async fn test_api_get_timestamp_proof() { let (mut testkit, _) = init_testkit(); let keypair ...
Rust
0
ocessors = plugin.processors processors_names = list(processors.keys()) processor1, processor2 = list(processors.values()) self.assertEqual(["my-processor-1", "my-processor-2"], processors_names) self.assertIsInstance(processor1, Processor) self.assertIsInstance(processor2, Proce...
Python
1
Utc::now().naive_utc(), updated: Utc::now().naive_utc(), }; // Check if the user to add exists use crate::user::User; match User::exists(conn, user_id_to_add) { Err(_) => return Err(DatabaseError), Ok(bool) => { ...
Rust
0
(SERIALIZE_FILE_NAME); // Create the engine.json file to hold the serialized data, and write it out to disk, let file = File::create(&filepath) .context(format!("Unable to create file {:?} for serialization", filepath))?; log::debug!("Writing serialized engine out to {:?}", filepath...
Rust
0
# ASN.1 "character string" types from pyasn1.type import univ, tag class UTF8String(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 12) ) encoding = "utf-8" class NumericString(univ.OctetString): tagSet = univ.OctetStri...
Python
1
ss(Some([HX, HX, HX, HX]))?; assert_eq!(game.turn(), Player::C); let (game, _) = game.play(HX).left().unwrap(); let (game, _) = game.play(HX).left().unwrap(); let (game, _) = game.play(HX).left().unwrap(); let (game, _) = game.play(HX).left().unwrap(); let (game, _) = gam...
Rust
0
TwoFloat { hi: hexf64!("0x1.5555555555555p-3"), lo: hexf64!("0x1.32460411c87c6p-57"), }, TwoFloat { hi: hexf64!("-0x1.6c16c16c16af3p-9"), lo: hexf64!("0x1.136a2c950fda6p-63"), }, TwoFloat { hi: hexf64!("0x1.1566abbf9f4f6p-14"), lo: hexf64!("0x1.1110477...
Rust
0
, PartialEq)] pub struct RibonucleicAcid { seq: String } impl RibonucleicAcid { pub fn new(seq: &str) -> RibonucleicAcid { // Well, none of the tests give us bad string inputs... RibonucleicAcid { seq: seq.to_owned(), } } } #[derive(Debug, PartialEq)] pub struct Deoxyri...
Rust
0
# -*- coding: utf-8 -*- # Copyright 2022 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 o...
Python
1
pub fn init() -> Self { return TempFs { fs: NewFs { fs_name: "TempFs" }, } } } <reponame>Nanai10a/icey_pudding use super::{RepositoryError, Result as RepoResult}; pub fn find_mut<T, P>(v: &mut [T], preficate: P) -> RepoResult<&mut T> where T: ::core::fmt::Debug, P: FnMut(&&mut T...
Rust
0
nseg: tgt = [tgt[t * len(tgt) // T] for t in range(T)] target[b][: len(tgt)] = torch.IntTensor(tgt) target_size[b] = len(tgt) loss = self.asg.forward(emissions, target.to(device), target_size.to(device)) if reduce: loss = torch.sum(loss) sa...
Python
1
(0xDE, 0xB8, 0x87); pub const CADET_BLUE: Self = Self::rgb(0x5F, 0x9E, 0xA0); pub const CHARTREUSE: Self = Self::rgb(0x7F, 0xFF, 0x0); pub const CHOCOLATE: Self = Self::rgb(0xD2, 0x69, 0x1E); pub const CORAL: Self = Self::rgb(0xFF, 0x7F, 0x50); pub const CORNFLOWER_BLUE: Self = Self::rgb(0x64, 0x95,...
Rust
0
tatic, R: Send + 'static, { } fn guard_size(unchecked: bool) -> usize { if !unchecked { #[cfg(feature = "memory-protection-unit")] return mpu::guard_size(); } 1 } #[allow(unused_variables)] unsafe fn mpu_config(unchecked: bool, stack_bottom: *mut u8) -> u32 { if !unchecked { ...
Rust
0
import torch import torch.distributions as dist import azua.models.bnn.distributions.matrix_normal as mn def _rand_psd(d, batch_shape=None): if batch_shape is None: batch_shape = tuple() elif isinstance(batch_shape, int): batch_shape = (batch_shape,) a = torch.randn(*batch_shape, d, d + 1...
Python
1
eq!(op2, 0); debug_assert_eq!(op3, 0); Vec::new() }; Self { base: OpCodeHandler { encode: Self::encode, try_convert_to_disp8n: Some(Self::try_convert_to_disp8n), operands: operands.into_boxed_slice(), op_code: get_op_code(enc_flags2), group_index, rm_group_index, enc_flags3, ...
Rust
0
tatic MAIN_LOOP: Lazy<DurationHistogram> = Lazy::new(|| { DurationHistogram::new( register_histogram!( "diem_state_sync_main_loop", "Duration of the each run of the event loop" ) .unwrap(), ) }); //////// 0L //////// /// Number of disabled peer events pub static...
Rust
0
Desc = cellDescClass("JKFFSRX2") Desc.properties["cell_footprint"] = "jkffsr" Desc.properties["area"] = "103.118400" Desc.properties["cell_leakage_power"] = "2534.502960" Desc.pinOrder = ['CK', 'IQ', 'IQN', 'J', 'K', 'Q', 'QN', 'RN', 'SN', 'next'] Desc.add_arc("CK","J","setup_rising") Desc.add_arc("CK","J","hold_rising...
Python
1
from functools import lru_cache class Solution: def next_higher_compute(self, arr): stack = [] self._next_higher = list(range(len(arr))) for _, pos in sorted(((n, p) for p, n in enumerate(arr))): while stack and stack[-1] < pos: self._next_higher[stack.pop()] = ...
Python
1
us, 0.0); // Draw the track arc let mut path = Path::new(); path.arc(centerx, centery, radius - span / 2.0, end, start, Solidity::Solid); let mut paint = Paint::color(background_color); paint.set_line_width(span); paint.set_line_cap(LineCap::Round); canvas.stroke...
Rust
0
rint(r[0].ring) b = RecordsDisplay(a, a, r) c = Frame(b) b.config(xscrollcommand=h.set) h.config(command=b.xview) b.config(scrollregion=c.bbox()) # Label(b, text="Hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii").pack() h.pack(side=BOTTOM, fill='x') b.pack() # def refresh(): # a.after(...
Python
1
async for event in runner.run_async( user_id=session.user_id, session_id=session.id, new_message=content ): # Forward state delta to parent session. if event.actions.state_delta: tool_context.state.update(event.actions.state_delta) last_event = event if runner.artifact_service...
Python
1
2) -> Result<Instant, Error> { let sys_time = self.ll.sys_time().read()?.value(); // This should always be the case, unless we're getting crap back from // the lower-level layer. assert!(sys_time <= TIME_MAX); // All of the following operations should be safe against undefined ...
Rust
0
::gpio::Speed; use stm32l4xx_hal::otg_fs::{UsbBus, USB}; use stm32l4xx_hal::prelude::*; use stm32l4xx_hal::rcc::{ ClockSecuritySystem, CrystalBypass, MsiFreq, PllConfig, PllDivider, PllSource, }; use stm32l4xx_hal::stm32::{Peripherals, CRS, PWR, RCC}; use usb_device::prelude::*; /// Enable CRS (Clock Recovery Syst...
Rust
0
import pandas as pd from io import StringIO import json import os from dotenv import load_dotenv load_dotenv() DEBUG = False def read_DB_csv_file(csv_file): """ Charger un fichier CSV (d'un chemin local ou d'une URL GitHub) et l'analyser dans un DataFrame pandas. """ # Vérifier si l'entrée est une URL...
Python
1
from . import test_delivery_window
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from hwt.code import If from hwt.synthesizer.unit import Unit from hwt.interfaces.std import Signal from hwt.interfaces.utils import addClkRstn, propagateClkRst from hwt.hdl.types.bits import Bits class addClkSyncRstn(Unit): def _declr(self): self.u8 ...
Python
1
def sayHello(name): print(f"Hello {name}") def sayBye(name): print(f"Bye {name}") def sayWelcome(name): print(f"Welcome {name}") def sayGoodBye(name): print(f"GoodBye {name}")
Python
1
at(ipix) for ipix in range(wcs.pixel_n_dim)]) + '\n') # fmt: on matrix = wcs.axis_correlation_matrix matrix_str = np.empty(matrix.shape, dtype="U3") matrix_str[matrix] = "yes" matrix_str[~matrix] = "no" for iwrl in range(wcs.world_n_dim): # fmt: off ...
Python
1
4, &mut sys_secs as *mut i64, &mut sys_us as *mut i64); } (usr_secs, usr_us, sys_secs, sys_us) } pub fn c_open_reporter(fname: String) { unsafe { open_reporter(fname.as_ptr()); } } pub fn c_write_reporter(msg: String) { //let n = unsafe { write_reporter(msg.as_ptr(), ...
Rust
0
251 => LinkType::BLUETOOTH_LE_LL, 253 => LinkType::NETLINK, 254 => LinkType::BLUETOOTH_LINUX_MONITOR, 255 => LinkType::BLUETOOTH_BREDR_BB, 256 => LinkType::BLUETOOTH_LE_LL_WITH_PHDR, 257 => LinkType::PROFIBUS_DL, 258 => LinkType::PKTAP, ...
Rust
0
\x13\xc0=Dr\xe2_\x13\xc7\x92B\x1fq\xd2\xfe\ \x88\xd4\x81\xb4\xd9<\xf2n]5\xd9\x04-\x9e\xc7\x97\ cIMY\xadN\x1d\x80$\xa9s\x1a\xadm\x8e \ J#\xdf\x0e<%mDRG,#6\xaa\xff\x10\ xA\xff\xe0\xc0^\x89\xe3\x99\xadO\xa6\x0e\xa0d<\ \xb4$I\x92\xaaj\x0c\xb8\x0e\xf80\xd5\x1c\x8c\x0d\xd1\ \x12h\x05m\x18\xa6\x5c\x10\x9b\x89k\xfc\x13\xf2=x\ ...
Python
1