text
string
label_name
string
labels
int64
changes: Vec::new(), }; let new_set = current_authorities.clone(); // We have three pending changes with 2 possible roots that are enacted // immediately on finality (i.e. standard changes). let change_a0 = PendingChange { next_authorities: new_set.clone(), delay: 0, canon_height: 5, canon_hash:...
Rust
0
e because the API key is not set." else: client = Mistral(api_key=api_key) model = "mistral-large-latest" chat_context = ( f"You are an AI assistant that provides information about GeoAI and Geographic Information Systems. " ...
Python
1
Script(script) => { with_ast_view_for_script(ScriptInfo { script, source_file: info.source_file, tokens: info.tokens, comments: info.comments, }, |script| with_view(Program::Script(script))) } } } pub fn with_ast_view_for_module<'a, T>(info: ModuleInfo, with_view: impl...
Rust
0
#!/usr/bin/env python3 # Copyright 2023 Canonical Ltd. # # 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...
Python
1
"""Check tasks for pyinvoke.""" # %% IMPORTS from invoke.context import Context from invoke.tasks import task # %% TASKS @task def poetry(ctx: Context) -> None: """Check poetry config files.""" ctx.run("poetry check --lock") @task def format(ctx: Context) -> None: """Check the formats with ruff.""" ...
Python
1
e KeyTemplate { type_url: crate::ECDSA_SIGNER_TYPE_URL.to_string(), value: serialized_format, output_prefix_type: prefix_type as i32, } } /// Return a [`KeyTemplate`] that generates a new ED25519 private key. pub fn ed25519_key_template() -> KeyTemplate { KeyTemplate { type_...
Rust
0
dex, index_to_type, vocabulary = load_vocabulary(input_directory+'voc.dat'); from vb.prior.tree.priortree import VocabTreePrior; prior_tree = VocabTreePrior(); prior_tree._initialize(input_directory+tree_name+".wn.*", input_directory+tree_name+".hyperparams", vocabulary); import inferencer lda_inf...
Python
1
PropertyGroup { value: Cow::Owned(self.value.clone()), } } pub fn with( existing: ChargeItemDefinition_PropertyGroup, ) -> ChargeItemDefinition_PropertyGroupBuilder { ChargeItemDefinition_PropertyGroupBuilder { value: (*existing.value).clone(), } ...
Rust
0
} } if let Some(suffix) = word_on_suffix(&text, &char_indices, index) { if let Some(val) = inner_map.get(&suffix[..]) { ret.push_str(val); continue; } } ret.push_str(str_); ...
Rust
0
,$k9,$<KEY>,$kf]); let s = [$s00,$s01,$s02,$s03,$s04,$s05,$s06,$s07, $s08,$s09,$s0a,$s0b,$s0c,$s0d,$s0e,$s0f, $s10,$s11,$s12,$s13,$s14,$s15,$s16,$s17, $s18,$s19,$s1a,$s1b,$s1c,$s1d,$s1e,$s1f, $s20,$s21,$s...
Rust
0
string, printf_arguments); } else { builder = builder.set_message(string) } } builder = builder.set_severity(severity); let mut result = Message::from(builder.build()); if severity_untrusted.is_some() && verbosity.is_some() { result.s...
Rust
0
lder.build(); let certificate_bytes: Vec<u8>; let private_key_bytes: Vec<u8>; match config.output_format { FileFormat::Pem => { certificate_bytes = certificate.to_pem().unwrap(); private_key_bytes = private_key.private_key_to_pem_pkcs8().unwrap(); } FileForma...
Rust
0
).expect("json config values"); // let org_access_token_json = config_vals["org_access_token"].to_string(); // let org_access_token = serde_json::from_str::<String>(&org_access_token_json) // .expect("organzation access token"); // let baseline: ApiClient = Baseline::factory(&org_access_token); /...
Rust
0
#[no_mangle] fn pdf_color_graycolor(color: *mut pdf_color, g: f64) -> i32; #[no_mangle] fn transform_info_clear(info: *mut transform_info); /* returns 1.0/unit_conv */ #[no_mangle] fn dev_unit_dviunit() -> f64; /* Draw texts and rules: * * xpos, ypos, width, and height are all fixe...
Rust
0
allback_result = callback_receiver.try_recv(); if !matches!(callback_result, Ok(Some(Ok(..)))) { panic!("Expected an okay result but got: {:?}", callback_result); } // TODO(joshlind): verify that mempool is sent the correct transactions! let (callback_sender, _callback_recei...
Rust
0
""" core_costvol.py Computes cross correlation between two feature maps. Written by Phil Ferriere Licensed under the MIT License (see LICENSE for details) Based on: - https://github.com/tensorpack/tensorpack/blob/master/examples/OpticalFlow/flownet_models.py Written by Patrick Wieschollek, Copyright Yux...
Python
1
evice[f_idx].copy() # device->camera pose = pose @ T_DEVICE_FROM_CAMERA.numpy() # Load images rgb_path = osp.join(scene_dir, "rgb", f"vignette{f_idx:07d}.jpg") depth_path = osp.join(scene_dir, "depth", f"depth{f_idx:07d}.png") rgb = imread_cv2(rg...
Python
1
import pandas as pd from sentence_transformers import SentenceTransformer from sklearn.metrics.pairwise import cosine_similarity import warnings warnings.filterwarnings('ignore') # 配置参数 CONFIG = { "data_path": "1.xlsx", # Excel文件路径 "sheet_name": "sheet", # 工作表名称 "model_name": "paraphrase-multilingual-Mi...
Python
1
# -*- coding: utf-8 -*- import re def storage_domain(): return 'https://drsgjxdg6zyfq.cloudfront.net' def election_year(county): return '2014' def county_abbr2string(abbr): return { 'ntp': u'新北市', 'tcc': u'臺北市', 'tycc': u'桃園市', 'kmc': u'基隆市', 'ilcc': u'宜蘭縣', ...
Python
1
build(resources, MainState { real_state: state }) .unwrap() .with_frame_limit(FrameRateLimitStrategy::Sleep, 60) .build(game_data_builder) .unwrap(); game.run(); } <filename>learn substrate/substrate-1.0/srml/aura/src/tests.rs // Copyright 2017-2019 Parity Technologie...
Rust
0
body = json.loads(body.decode('utf-8')) await self._handle_command(body) except asyncio.CancelledError: raise except Exception: logger.error('room=%d, body=%s', self.room_id, body) ...
Python
1
from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views app_name = "main" urlpatterns = [ path('', views.index,), path('login/', views._login, name='login'), path('logout/', views._logout, name='logout'), path('usercenter/', views.i...
Python
1
<th class="right">{"Acquisition Date"}</th> <th class="right">{"Book Value"}</th> </tr> }]; let mut entries = holdings.iter().collect::<Vec<_>>(); entries.sort_by_key(|t| t.0); for (account, account_map) in entries { if ...
Rust
0
#[test] fn it_works() { unsafe { let mut bp1 = std::mem::MaybeUninit::<blst_p1>::zeroed().assume_init(); //let mut bp1_aff = std::mem::MaybeUninit::<blst_p1_affine>::zeroed().assume_init(); blst_p1_add_or_double_affine(&mut bp1, &bp1, &BLS12_381_G1); //...
Rust
0
return Err(error); } let ciphersuite = Config::ciphersuite(ciphersuites[0]).unwrap(); let leaf_node_secret = derive_leaf_node_secret(&leaf_secret); let keypair = ciphersuite.derive_hpke_keypair(&leaf_node_secret); Self::new_with_keypair( ciphersuites, ...
Rust
0
self.STATE[fd][2].state = "closing" self.state_machine(fd) print(msg) return def aclose(self, fd): try: print 'Error: %s:%d' %(self.STATE[fd][1][0] ,self.STATE[fd][1][1...
Python
1
label = emotions[i][0] colour = colors[emotions[i][1]] i += 1 plot_one_box(xyxy, im0, label=label, color=colour, line_thickness=opt.line_thickness) # Stream results if view_img: disp...
Python
1
A -> C -> D -> A /// let graph = vec![ /// Vertex("A", vec![1, 3, 2]), // 0 /// Vertex("B", vec![3]), // 1 /// Vertex("C", vec![3]), // 2 /// Vertex("D", vec![0]), // 3 /// ]; /// /// let start = &graph[0]; // A /// /// // `&tree` represents the root `Vertex`. /// // The `FnMut(&Verte...
Rust
0
::BeforeMiddleware; use iron::Url; use iron::headers::Headers; use iron::request::Request; use iron::response::Response; use iron_test::request; fn test_middleware(url: &str, headers: &[(&str, &[u8])], result: &str) { let mut h = Headers::new(); for &(k, v) in headers { ...
Rust
0
::{BILLION, MICROSECOND, MILLION, PERCENTILES}; use crate::config::Config; use crate::samplers::Sampler; use crate::stats::{record_distribution, register_distribution}; use bcc; use bcc::core::BPF; use failure::*; use logger::*; use metrics::*; use time; use std::collections::HashMap; pub struct Block<'a> { conf...
Rust
0
else { self.a_pack.set_capacity(capacity_for_apt); } self.a_pack.send_alias(thr); } //Logically resize the a_pack matrix self.a_pack.resize_to(a, y_marker, x_marker, &self.algo_desc); <Packer<T, At, APt>>::pack(a, &mut self.a_pack, thr); ...
Rust
0
t, 'w') print "Writing file" #Boucles for i in range(size[0]): # les lignes for j in range(size[1]): value = SortedTable[i][j] tmp = (int)(value/64) pix[i,j] = (tmp,tmp,tmp) if(j==(size[1]-1)): targetFile.write(str(value)) else: targetFile.write(str(value)+";") targetFile.write("\n") targetFile...
Python
1
import torch from util.save_reference import save_reference from typing import Tuple, List, Iterable import einops def create_tensors( shape: Tuple[int, ...] | List[int] | Iterable[int], value = -2, dtype: torch.dtype = torch.int64, x = None, ): assert (shape is None and x is not N...
Python
1
t_fp_eq!(acond, 43.39603897); assert_fp_eq!(acond, a.cond_nt(MatNorm::Entrywise(Norm::L2)).unwrap()); let b = a.t() * &a; let bcond = b.cond_nt(MatNorm::Frobenius).unwrap(); assert_fp_eq!(bcond, 1538.9530598); assert_fp_eq!(bcond, b.cond_nt(MatNorm::Entrywise(Norm::L2)).unwrap()...
Rust
0
); is_biggest = false; } } } } fn print_this_node(node_to_print: &Node, is_biggest: bool, depth: u8, indentation_str: &str) { let padded_size = format!("{:>5}", human_readable_number(node_to_print.entry().size()),); println!( "{} {} {}", if is...
Rust
0
cept epsilon = LinearPrior( slope=Prior( dist_name="Normal", dist_params=(0, 2), ), intercept=Prior( dist_name="Normal", dist_params=(0.0, 1.0), ), basis_function=BsplineBasisFunction(basis_column=0, nknots=5, degree=3), ) ...
Python
1
: torch.tensor(ms_ssims).mean().item(), # "D-SSIM": torch.tensor(Dssims).mean().item() # }) per_view_d...
Python
1
d = [int(a) for a in input().split()] p, i, j, n = d[-1], -1, 0, len(d) while j < n: if d[j] <= p: i+=1 d[i],d[j] = d[j],d[i] j+=1 print(d)
Python
1
from parsers import base import collections class Parse(base.Parser): """ Appen.com 2020 breach data parser Source File SHA-1: 97248cc3aa42dd3a6bd6b80df88a6d26b630c294 Appen.txt Good Lines: 1,219,865 """ name = "None" web = "appen.com" year = "2020" def row_format(se...
Python
1
*64]; let mut stats = SpawnableTaskStats{ iterations: 0, // custom_stats: None, }; let this = thread_this; loop { let mut this = this.lock().unwrap(); let res = Self::werk(&mut this, &mut buf[..]); ...
Rust
0
from models.models import Category from pylord.app import PyLordApp from database import get_db from .secret_keys import auth_required from .dynamic_handlers import update_handler from models.models import User app = PyLordApp() @app.route("/create_category", allowed_methods=['post']) @auth_required def create_catego...
Python
1
t wchar_t; } extern "C" { pub fn putwc(_Character: wchar_t, _Stream: *mut FILE) -> wint_t; } extern "C" { pub fn putwchar(_Character: wchar_t) -> wint_t; } extern "C" { pub fn _putws(_Buffer: *const wchar_t) -> ::std::os::raw::c_int; } extern "C" { pub fn ungetwc(_Character: wint_t, _Stream: *mut FILE) ...
Rust
0
# %% import openai from utils import save_jsonl # %% import json eli5_data = [] no_eli5_data = [] with open("eli5.jsonl", "r") as f: for line in f.readlines(): data = json.loads(line.strip()) messages = [ {"role": "user", "content": data["question"]}, {"role": "assistant", "...
Python
1
# # THIS INIT FILE IS WRITTEN FOR BLENDER, THANKS TO THIS IT CAN BE ADDED AS BLENDER ADDON # import bpy from PySide2 import QtGui, QtCore, QtWidgets from .ExportOpenEMSDialog import * bl_info = { "name": "OpenEMS Simulation", "author": "Lubomir Jagos", "version": (0, 1), "blender": (2, 80, 0), "...
Python
1
{ if gui::show_menu(ctx) == gui::MenuResult::Cancel { newrunstate = RunState::AwaitingInput; } } } { let mut runwriter = self.ecs.write_resource::<RunState>(); *runwriter = newrunstate; } damage_syst...
Rust
0
he failure. Note that Shuttle //! isn't doing anything special to increase the probability of this test failing other than running //! the body multiple times. //! //! When this test fails, Shuttle provides output that can be used to **deterministically** //! reproduce the failure: //! //! ```text //! test panicked in ...
Rust
0
import typing from BaseClasses import Item, ItemClassification from .Names import ItemName class ItemData(typing.NamedTuple): code: typing.Optional[int] progression: bool trap: bool = False quantity: int = 1 event: bool = False class SMWItem(Item): game: str = "Super Mario World" # Separa...
Python
1
cmyk().unwrap()); // print!("{:?}, ", color.to_cmyk().unwrap()); } // println!("],"); } } #[test] fn test_rgb_tohsv() { let rgb_vec = vec!["rgb( 81% , 89% , 10%)", "rgba(81%,89%,10%,0.5)", "rgba(81,89,12,0.3)"]; let rgb_result = vec![ vec!["hsv(66.08,88.76%,89%)", "HSV(66.08,88.76%,89%)", "hsv(66.0...
Rust
0
options.add(option_name) msg.page_profile.config.extend(config_options) # Check the predefined set of modules for attribution attributions: set[str] = { attribution for attribution in _ATTRIBUTIONS_TO_CHECK if attribution in sys.modules } msg.page_profile.os = str(sys.plat...
Python
1
e().unwrap().to_wildcard()) } } const STACK_SIZE: usize = 16; #[derive(Default)] pub struct Stack { pub stack: [u16; STACK_SIZE], pub pointer: u8, } impl Stack { pub fn new() -> Self { Default::default() } pub fn push(&mut self, value: u16) { assert!((self.pointer as usize) < ...
Rust
0
/// ``` /// pub fn sysclock_set_divider(syscon: &lpc1347::SYSCON, divider: u8) { unsafe { syscon.sysahbclkdiv.modify(|_, w| w.div().bits(divider)); } } /// Initializes the watchdog /// /// # Arguments /// * `wd_int_enable` - Enable the watchdog timer interrupts * `wwdt_clk_src` - Select the clock sour...
Rust
0
enabled: true, listen_addr: Ipv4Addr::new(127, 0, 0, 1), listen_port: 0, allow_origin: None, allocator_metrics_enabled: true, }, chain: None, db_path: None, freezer_db_path: None, ...
Rust
0
f i == i0 || i == i1 { continue; } let r = p0.circumradius2(p1, p); if r < min_radius { i2 = i; min_radius = r; } } if min_radius == f64::INFINITY { None } else { // swap the order of the seed points for counter-clockwise o...
Rust
0
assert_eq!(g2d.halo[3], [0.4999, 0.5001]); let mut g3d = get_test_grid_3d()?; g3d.set_halo(&[0.5, 0.5, 0.5]); assert_eq!(g3d.halo[0], [0.4999, 0.4999, 0.4999]); assert_eq!(g3d.halo[1], [0.5001, 0.4999, 0.4999]); assert_eq!(g3d.halo[2], [0.5001, 0.5001, 0.4999]); as...
Rust
0
from collections import deque # 덱을 임포트 해온다. def solution(maps): answer = bfs(0,0,maps) # bfs 사용을 위해 따로 bfs라는 함수를 만들고 여기에 인자로 시작점(0,0)과 배열 maps를 전달 return -1 if answer == 1 else answer # 축약한 if문 표현이다 answer이 최종적으로 1이라면 -1을 반환하고 아닐 경우 bfs 결과값을 반환. def bfs(x,y,maps): que = deque() # deque를 초기화 해준다. dx =...
Python
1
ns_12 = || Some(btreemap! {1=>node(), 2=>node()}); let ns_123 = || Some(btreemap! {1=>node(), 2=>node(), 3=>node()}); let ns_1234 = || Some(btreemap! {1=>node(), 2=>node(), 3=>node(), 4=>node()}); let res = m().set_nodes(None)?; assert_eq!(&None, res.get_nodes()); let res = m().set_nodes(ns_123())...
Rust
0
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["color"] = "red" print(thisdict)
Python
1
import tkinter as tk from tkinter import ttk, messagebox import ttkbootstrap as ttk from ttkbootstrap.constants import * from constants import ICON_PATH, resource_path from utils import parse_input, save_settings class SettingsWindow(ttk.Toplevel): def __init__(self, parent, settings, callback): super()...
Python
1
<I>, I: Instance> InitializeMembers<T::AccountId> for Module<T, I> { fn initialize_members(members: &[T::AccountId]) { if !members.is_empty() { assert!(Members::<T, I>::get().0.is_empty(), "Members are already initialized!"); Members::<T, I>::put(OrderedSet::from_sorted_set(members.into())); } } } impl<T: ...
Rust
0
"""API models for VCS integrations.""" from __future__ import annotations from pydantic import BaseModel, Field, SecretStr from tracecat.vcs.github.manifest import GitHubAppManifest class GitHubAppInstallRequest(BaseModel): """Request to set GitHub App installation ID for workspace.""" installation_id: in...
Python
1
.result(&ref_date, 100.0).unwrap().ytm), ytm); } #[test] fn zero_cpn_bond() { let bond = FixedBond { value_date: NaiveDate::from_ymd(2010, 1, 1), mty_date: NaiveDate::from_ymd(2011, 1, 1), redem_value: 100.0, cpn_rate: 0.05, cpn_freq: to_cp...
Rust
0
# 1. data img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True) size_divisor = 32 data_pipeline = [ dict(typename='LoadImageFromFile'), dict( typename='MultiScaleFlipAug', img_scale=(1100, 1650), flip=False, transforms=[ dict(typename='...
Python
1
Fixture, Yarn1Fixture, YarnBerryFixture, }; use hamcrest2::assert_that; use hamcrest2::prelude::*; use test_support::matchers::execs; use volta_core::error::ExitCode; fn package_json_with_pinned_node(node: &str) -> String { format!( r#"{{ "name": "test-package", "volta": {{ "node": "{}" }} }}"#,...
Rust
0
1. Enter your custom model provider's API key (if required), base URL, and model name. 2. Select your industry and company size from the sidebar. 3. Go to the `Threat Group Scenarios` page to generate a scenario based on a threat actor group's known techniques, or go to the `Custo...
Python
1
return dimensions[0] # Ignore empty dimensions. (They should not reduce the size of others.) dimensions = [d for d in dimensions if not d.is_zero()] if dimensions: # Take the highest minimum dimension. min_ = max(d.min for d in dimensions) # For the maximum, we would pref...
Python
1
:f00::1002".parse::<Ipv6Addr>().unwrap(); let v62 = "2001:db8:f00::2001".parse::<Ipv6Addr>().unwrap(); assert!(v41 < v42); assert!(v61 < v62); assert_eq!(v41, IpAddr::V4(v41)); assert_eq!(v61, IpAddr::V6(v61)); assert!(v41 != IpAddr::V4(v42)); assert!(v61 != IpAddr::V6(v62)); assert!(v...
Rust
0
4")] /// Encoded (non-ASCII characters) representation of the <a href="tag_58_Text.html" target="bottom">Text&nbsp;(58)</a> field in the encoded format specified via the <a href="tag_347_MessageEncoding.html" target="bottom">MessageEncoding&nbsp;(347)</a> field. #[serde(skip_serializing_if = "Option::is_none")] #[se...
Rust
0
import networkx as nx import numpy as np import argparse import os import pickle import glob from multiprocessing import Pool from functools import partial # 导入CodeEmbedder类 from embedding import CodeEmbedder def parse_options(): parser = argparse.ArgumentParser(description='Image-based Vulnerability Detection.') ...
Python
1
ialog: # Dummy class for testing file display functions. idle_credits = About.show_idle_credits idle_readme = About.show_readme idle_news = About.show_idle_news # Called by the above display_file_text = About.display_file_text _utest = True class DisplayFileTest(unittest.TestCase): """...
Python
1
ta[0], ctxt, vars) break elif kind is EXEC: _exec_suite(data, ctxt, vars) else: yield kind, data, pos else: if not stack: break stream = pop() def _include(...
Python
1
class Solution: def countMaxOrSubsets(self, nums: List[int]) -> int: prevBits = Counter([0]) for num in nums: for prev, count in list(prevBits.items()): prevBits[prev | num] += count return prevBits[reduce(lambda a,b: a | b, nums)]
Python
1
from fastapi import FastAPI, UploadFile, File, Form, Depends, HTTPException from sqlalchemy.orm import Session import os from . import database, models, crud, utils, schemas app = FastAPI() models.Base.metadata.create_all(bind=database.engine) def get_db(): db = database.SessionLocal() try: yield db ...
Python
1
dater, BuffDisplayedState.ALLY_SUPPORT: _AllySupportStateUpdater, BuffDisplayedState.JUGGERNAUT: _JuggernautStateUpdater, BuffDisplayedState.SURE_SHOT: _SureShotStateUpdater, BuffDisplayedState.CONCENTRATION: _ConcentrationStateUpdater, BuffDisplayedState.MARCH: _MarchStateUpdater, BuffDisplayedState.AGGRESSIVE_D...
Python
1
let camera = Camera { eye: glm::vec3(0.0, 0.0, -8.0), up: glm::vec3(0.0, -1.0, 0.0), look_at: CameraLookAt::Dir(glm::vec3(0.0, 0.0, 1.0)) }; State { render_mode: RenderMode::Standard, run: true, window_resized: false, c...
Rust
0
ier(s)" bl_options = {'REGISTER', 'UNDO'} def execute(self, context): scn = context.scene prop = scn.arraytools_prop at_array.add_del_modifiers(prop) return {'FINISHED'} class ANIM_OT_anim_info(bpy.types.Operator): """Shows an info message for animation""" bl_idname = ...
Python
1
b = _mm_aesdec_si128(b, keys[2]); b = _mm_aesdec_si128(b, keys[1]); b = _mm_aesdeclast_si128(b, keys[0]); _mm_storeu_si128(block.as_mut_ptr() as *mut __m128i, b); } } #[inline] fn encrypt_blocks(&self, blocks: &mut Block128x8) { unsafe { ...
Rust
0
#[inline] pub fn variant(self, variant: SETCLR6W) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Independent. Set and clear do not depend on any counter."] #[inline] pub fn independent(self) -> &'a mut W { self.variant(SETCLR6W::INDEPENDENT) } #[doc = "L coun...
Rust
0
def test_stable_diffusion_gligen_k_euler_ancestral(self): device = 'cpu' components = self.get_dummy_components() sd_pipe = StableDiffusionGLIGENTextImagePipeline(**components) sd_pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(sd_pipe .scheduler.config) sd_pipe = sd_pipe.to(dev...
Python
1
# Copyright (C) 2024 Callum Dickinson # # Buildarr is free software: you can redistribute it and/or modify it under the terms of the # GNU General Public License as published by the Free Software Foundation, # either version 3 of the License, or (at your option) any later version. # # Buildarr is distributed in the hop...
Python
1
""" Diffraction Pattern =================== Computes the diffraction pattern from an array of circular apertures. """ # %% # sphinx_gallery_start_ignore # sphinx_gallery_thumbnail_number = 2 # sphinx_gallery_end_ignore import matplotlib.pyplot as plt import torch import torchoptics from torchoptics import Field, v...
Python
1
e_add(self.update_location_and_weather) except requests.exceptions.HTTPError as e: print(f"API Error fetching weather data: {e}") GLib.idle_add(self.show_error, "API Error", "The weather service returned an error.") except requests.exceptions.RequestE...
Python
1
}; use hal::dma; #[derive(Copy, Clone, Debug)] pub enum Error { Overrun, ModeFault, Crc, } type R = Result<u32, Error>; __define_spis!{$($spi => ($gpio, $sclk, $miso, $mosi, $af))+} }; } <filename>bin/wlanstack/src/service.rs<gh...
Rust
0
pEX%SU--SX-- - -nM [R "X-S:USU- U--[R 5$)Nrrrrrrdrir{ziprcombr}r)rrr}r(kicnks rJr#genpareto_gen._munp.<locals>.__munp |C !QU#A...
Python
1
} <filename>src/cli/builder/auth.rs use crate::cli::opts::types::Authentication; use crate::core::transport::auth; use std::io; pub enum Authenticator { None(auth::NoopAuthenticator), Sha256(auth::Sha256Authenticator), Sha512(auth::Sha512Authenticator), } impl Authenticator { pub fn new( authe...
Rust
0
# Copyright 2024 the LlamaFactory team. # # 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 agreed to i...
Python
1
# Verificar que la imagen existe if not os.path.exists(image_path): return "ERROR: La imagen no existe: " + image_path # Paso 1: Analizar la imagen con Granite Vision print(f"Analizando imagen: {image_path}") info_extraida = analizar_imagen(image_path) ...
Python
1
}', '\u{2558}', '\u{2552}', '\u{2553}', '\u{256B}', '\u{256A}', '\u{2518}', '\u{250C}', '\u{2588}', '\u{2584}', '\u{258C}', '\u{2590}', '\u{2580}', '\u{03B1}', '\u{00DF}', '\u{0393}', '\u{03C0}', '\u{03A3}', '\u{03C3}', '\u{00B5}', '\u{03C4}', '\u{03A6}', '\u{0398}', '\u{03A9}', '\u{03B4}', '\u{221E}', '\u{...
Rust
0
# MenuTitle: Build small letter SM, TEL # -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals __doc__ = """ Creates the glyphs: servicemark, telephone. """ from GlyphsApp import Glyphs, GSGlyph, GSComponent from mekkablue.geometry import transform, offsetLayer expansion = 5 newGlyp...
Python
1
n(&Q) -> R, I: Clone { let mut mapped = Automaton::new(); for (state, clauses) in self.state_clauses.iter() { let state = g(state); for (f, clause) in clauses.iter() { for conjunction in clause.iter() { let mapped_conjunction = conjunction.it...
Rust
0
# Tracker (CalorieMixin) # Атрибути: private __activities # Методи: add_activity(), total_burned() from oop_mixin_tasks.fitness_app.activity import Activity from oop_mixin_tasks.fitness_app.calorie_mixin import CalorieMixin class Tracker(CalorieMixin): def __init__(self): self.__activities: list[Activity]...
Python
1
differences = {} p_value_differences = {} algorithms = list(scores_arrays.keys()) # Calculate differences for unique pairs of algorithms for i, alg_a in enumerate(algorithms): for alg_b in algorithms[i+1:]: # Start from the next algorithm to avoid duplicate...
Python
1
from functools import cache # partitially based on idea of # https://stackoverflow.com/questions/52534211/python-type-hinting-with-db-api/77350678#77350678 and from typing import TYPE_CHECKING if TYPE_CHECKING: from _typeshed.dbapi import DBAPIConnection, DBAPICursor else: DBAPIConnection = any DBAPICurs...
Python
1
import turtle as t import pandas as pd # Retrieving states name and coordinates all_states = pd.read_csv("50_states.csv") check_state = all_states["state"].tolist() screen = t.Screen() screen.title("U.S States Games") img = "blank_states_img.gif" screen.addshape(img) t.shape(img) guessed_state = [] while len(gues...
Python
1
from flask import Flask, request, jsonify import joblib import pandas as pd import pickle app = Flask(__name__) model = joblib.load(r"final_time_model.pkl") col_names = joblib.load(r"pace_column_names.pkl") @app.route("/") def hello() -> str: return "Hello World from Flask!" def pace_to_time(pace): hr, min,...
Python
1
3 = slim.conv2d(pool5, 1024, [3,3], rate=18, scope='fc6_3') fc6_3 = slim.dropout(fc6_3, 0.5, is_training=is_training, scope='drop6_3') fc7_3 = slim.conv2d(fc6_3, 1024, [1,1], scope='fc7_3') fc7_3 = slim.dropout(fc7_3, 0.5, is_training=is_training, scope='drop7_3') ...
Python
1
rt_eq!(x.coeff, 123456_i128 * 4); } #[test] fn test_mul_assign_int() { let mut x = Decimal::<2>::new_raw(123456); x *= 2_i8; assert_eq!(x.coeff, 123456_i128 * 2); x *= &-1234567890_i128; assert_eq!(x.coeff, 123456_i128 * 2 * -1234567890_i128); } #[test] ...
Rust
0
# Ultroid - UserBot # Copyright (C) 2021-2023 TeamUltroid # # This file is a part of < https://github.com/TeamUltroid/Ultroid/ > # PLease read the GNU Affero General Public License in # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>. import re from . import * STRINGS = { 1: """🎇 **Thanks for De...
Python
1
Error = ParseError; fn try_from(value: &[u8]) -> Result<Self, Self::Error> { Ok(Self::try_parse(value)?.0) } } impl GetFBConfigsReply { /// Get the value of the `length` field. /// /// The `length` field is used as the length field of the `property_list` field. /// This function compute...
Rust
0
grad.backward(losses['loss']) # self.depth_optimizer.step(self.opt.batch_size, ignore_stale_grad=True) # # if self.use_pose_net: # self.pose_optimizer.step(self.opt.batch_size, ignore_stale_grad=True) # # train_loss += losses['loss'].asscalar() # tbar.set_...
Python
1
logger.info('Loading model %s' % filename) saved_params = torch.load( filename, map_location=lambda storage, loc: storage ) all_dicts = saved_params['all_dicts'] state_dict = saved_params['state_dict'] epoch = saved_params['epoch'] optimizer = saved_pa...
Python
1