text
string
label_name
string
labels
int64
import torch def top_k(gradients, k): # num_elements = gradients.numel() # num_keep = int(k * num_elements) # 使用 torch.topk 函数找出梯度绝对值中最大的 num_keep 个元素及其对应的索引 # 确保 k 不超过 gradients 的大小 k = min(k, gradients.numel()) # 使用 numel() 获取元素总数 _, indices = torch.topk(torch.abs(gradients), k) spars...
Python
1
# -*- coding: utf-8 -*- import collections import re import concierge.core import concierge.core.exceptions as exceptions import concierge.utils Token = collections.namedtuple( "Token", ["indent", "option", "values", "original", "lineno"]) RE_QUOTED_SINGLE = r"'(?:[^'\\]|\\.)*'" RE_QUOTED_DOUBLE = r'"(?:[...
Python
1
closed if non-zero. /// `pline` is an out parameter to hold the created polyline. #[no_mangle] #[must_use] pub unsafe extern "C" fn cavc_pline_create( vertexes: *const cavc_vertex, n_vertexes: u32, is_closed: u8, pline: *mut *mut cavc_pline, ) -> i32 { ffi_catch_unwind!({ let mut result = Po...
Rust
0
let result = self.solve_as_type(solving_context, &solver_info.as_type_info()); match result { SolverResult::Solved(solved) => SolverResult::Solved(solved.map(|inner_type| { TypeMember::PropertySignature(PropertySignature { inner_type, name:...
Rust
0
from sympy.matrices import * import numpy def quat_multiply(q,r): """ Compute the quaternion multiplication t = q * t """ q0,q1,q2,q3 = q r0,r1,r2,r3 = r t = Matrix([r0*q0-r1*r1-r2*r2-r3*q3, r0*q1+r1*q0-r2*q3+r3*q2, r0*q2+r1*q3+r2*q0-r3*q1, r0*q3-r1*q2+r2*q1+r3*q0]) return t def quat_inv(q): """ Return ...
Python
1
""" NOT implemented yet """ # scheduler.py # Responsible for splitting tasks into subtasks, assigning worker nodes, and collecting results class Scheduler: def __init__(self): # Initialize job queue and list of available workers self.job_queue = [] self.worker_registry = {} # Worker IPs a...
Python
1
""" peagen.handlers.validate_handler ──────────────────────────────── Async entry-point for generic *validate* tasks (schema / semantic checks). Changes vs. legacy ------------------ * **worktree required** – handler operates inside an existing task work-tree supplied via ``task.args["worktree"]``; no cloning logic....
Python
1
from ..input import input_vasp_potcar, get_info, input_vasp_kpoints from ..shell_scripts import job from .. import __shell__, __python__, run_vasp_gam, run_vasp from ase.io import read from . import vasp_incar import os, shutil def gen_INCAR(encut, pressure, spin, fermiDirac, fun, u, fElectron, tBegin, tEnd, **kwargs...
Python
1
evice_id, # 指定设备ID 'shell', 'am', 'start', '-n', launch_cmd ]) # 等待应用启动 time.sleep(6) logger.info(f"{app_name}启动成功") return True except Exception as e: logger.error(f"启动应用失败:{str...
Python
1
lr # Training parameters BATCH_SIZE = args.batch_size EPOCHS = args.epochs model = None if MODEL_TOKEN == 'sahp': with autograd.detect_anomaly(): params = args, process_dim, device, tmax, \ train_times_tensor, train_seq_types, train_seq_lengths, \ ...
Python
1
ew pub fn offer_storage_available(&self, owner_id: &AccountId) -> u64 { let mut offer_count = 0; let offers_by_maker_id = self.offers_by_maker_id.get(owner_id); if offers_by_maker_id.is_some() { offer_count = offers_by_maker_id.unwrap().len(); } let offer_storage_count = self.offer_storage_by_owner_id.ge...
Rust
0
rage Rain Fall by Zone') ax1.set_xlabel('Zone') ax1.set_ylabel('Average Rain Fall') self.fig1.tight_layout() buf1 = io.BytesIO() self.fig1.savefig(buf1, format='png') buf1.seek(0) pixmap1 = QPixmap() pixmap1.loadFromData(buf1.getvalue()) scene1 = ...
Python
1
d we will resort to memcpy if left_input.last() <= right_input.first() { output_slice[..left_input.base_length()].copy_from_slice(left_input); output_slice[left_input.base_length()..].copy_from_slice(right_input); } else if right_input.last() < lef...
Rust
0
reid_embeddings, node_feats = self._load_appearance_data() # Determine graph connectivity (i.e. edges) and compute edge features edge_ixs, edge_feats_dict = self._get_edge_ixs(reid_embeddings) #print(edge_ixs.shape) if edge_feats_dict is None: edge_feats_dict = comput...
Python
1
# question 17 # Write a program in python that converts the given string in title case . str1=input("enter the string:") res=str1.title() print("updated string is: ",res)
Python
1
relude::*; pub struct Zset { dict: Dict<RobjPtr, RobjPtr>, list: SkipList, } impl Zset { pub fn new() -> Zset { Zset { dict: Dict::new(hash::string_object_hash, rand::thread_rng().gen()), list: SkipList::new(), } } }extern crate lru; use lru::LruCache; use crat...
Rust
0
#!/usr/bin/env python3 """ 🌳 Visualisation d'un arbre de décision du modèle Baseline Champion v2.3 Génère une prévisualisation interactive d'un arbre représentatif """ import joblib import pandas as pd import numpy as np from sklearn.tree import export_text, plot_tree import matplotlib.pyplot as plt from dtreeviz imp...
Python
1
_repr() .as_ref() .iter() .copied() .rev() .collect::<Vec<_>>() .as_slice(), ) .into_iter() .rev() .collect::<Ve...
Rust
0
: Zeroable, const N: usize, const M: usize> Zeroable for mat<T, N, M> {} unsafe impl<T: Pod, const N: usize, const M: usize> Pod for mat<T, N, M> {} pub type mat2x2<T = f32> = mat<T, 2, 2>; pub type mat3x2<T = f32> = mat<T, 3, 2>; pub type mat4x2<T = f32> = mat<T, 4, 2>; pub type mat2x3<T = f32> = mat<T, 2, 3>; pub t...
Rust
0
@lru_cache() def bytes_to_unicode(): """ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in y...
Python
1
import cloup as click from ofscraper.utils.args.parse.groups.check_content import url_group from ofscraper.utils.args.parse.group_bundles.check import main_check, common_args_check from ofscraper.utils.args.parse.group_bundles.advanced_common import advanced_args from ofscraper.utils.args.parse.group_bundles.utils.che...
Python
1
0, 0x0F, 0xFF, ]" ); } } <reponame>gaoyifan/powerline-rust<filename>src/theme.rs<gh_stars>0 use crate::modules::*; use crate::Color; #[derive(Copy, Clone)] pub struct SimpleTheme; impl CmdScheme for SimpleTheme { const CMD_FAILED_BG: Color = Color(161); const CMD_FAILED_FG: Color = Color(15); c...
Rust
0
OrValue<BatchId> { assert!(self.promise_result_succeeded(), GET_ACCOUNT_FAILURE); let unstaked_balance = staking_pool_account.unstaked_balance.0; // if unstaked balance is zero, then it means the unstaked NEAR funds were withdrawn // - unstaked NEAR is restaked to add liquidity, which e...
Rust
0
assembly, io::stdout()).unwrap(); } } } <gh_stars>1-10 //! Implementation of in-band secret distribution for Zcash transactions. use blake2_rfc::blake2b::{Blake2b, Blake2bResult}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use crypto_api_chachapoly::{ChaCha20Ietf, ChachaPolyIetf}; use ff::...
Rust
0
AtomicUsize::new(0)); let data = TestData::new(num.clone()); assert_eq!(num.load(Ordering::SeqCst), 1); let srv = test::start(move || { let data = data.clone(); App::new() .data(data) .service(web::resource("/").to(|_data: Data<TestData>|...
Rust
0
tring::from_utf8(val.bytes)?; Ok(Value::Json(utf_json.into())) } fn proto_string(val: String) -> Result<Value, QueryError> { Ok(Value::String(val.into())) } struct RawJsonBytes { bytes: Vec<u8> } impl<'a> FromSql<'a> for RawJsonBytes { fn from_sql(ty: &Type, mut raw: &'a [u8]) -> Result<Self, Box<dy...
Rust
0
self.logger.output_file("LOG-SSH: Skipping Public Key - %s" % keyfile_path) continue pool.add_task(self.sshlogin, ip, port, user, keyfile_path, self.args.timeout) else: pool.add_task(self.s...
Python
1
import torch import torch.nn as nn from . import basicblock as B import numpy as np class NonLocalUNet(nn.Module): def __init__(self, in_nc=3, out_nc=3, nc=[64,128,256,512], nb=1, act_mode='R', downsample_mode='strideconv', upsample_mode='convtranspose'): super(NonLocalUNet, self).__init__() down_n...
Python
1
"""CodeProject.AI constants.""" from typing import Final COMPONENT = "codeprojectai" PLATE_RECOGNITION_URL_BASE = "http://{host}:{port}/v1/image/alpr" # CONFIG_SCHEMA constants CONFIG_OBJECT_DETECTOR = "object_detector" CONFIG_FACE_RECOGNITION = "face_recognition" CONFIG_LICENSE_PLATE_RECOGNITION = "license_plate_r...
Python
1
from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from typing import List import crud import schemas from database import get_db from routers.auth import get_current_user router = APIRouter(prefix="/analytics", tags=["analytics"]) @router.get("/stats", response_model=sc...
Python
1
help for the available options.", subcommand, subcommand), Error::RequiredAttributes => write!(f, "Creating a schema requires at least one attribute. Please supply them via the --attributes flag."), Error::InvalidConfigurationStructure => write!(f, "Invalid configuration structure. Please make s...
Rust
0
HandleResponse = handle(&mut deps, env, msg).unwrap(); let rewards_per_roll_log = res.log.get(1).expect("no data"); let number_of_rolls_log = res.log.get(2).expect("no data"); assert_eq!( &log( "rewards_per_roll", &(Decimal::from_ratio(1000000u128, 1u128).to_string() + "uus...
Rust
0
teger=8, signed=true>(-123.0)", ); // resolution = 0.5 assert_eq!( format!("{:?}", FXP::<4, 3, false>::from_float(2.5)?), "FXP<word=4, integer=3, signed=false>(2.5)", ); assert_eq!( format!("{:?}", FXP::<4, 3, true>::from_float(-2.5)?), ...
Rust
0
# -*- coding: utf-8 -*- # Copyright 2020 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
<usize>().unwrap() - 1; let v2 = words.next().unwrap().parse::<usize>().unwrap() - 1; graph[[v1, v2]].weight = 1; } None => return Err(io::ErrorKind::InvalidInput.into()), } } // graph.add_indirect_edges(); Ok(graph) } impl Graph { pub f...
Rust
0
e) { println!("{:#?}", package_info); } else { return Err(anyhow!("Failed to read package information.")); } Ok(()) } /// /// /// pub fn list() -> Result<()> { let packages_dir = get_packages_dir(); if !packages_dir.exists() { println!("No packages found."); return ...
Rust
0
t(ScmpArch::X86).unwrap(); assert!(!ret); } #[test] fn test_merge_filters() { let mut ctx1 = ScmpFilterContext::new_filter(ScmpAction::Allow).unwrap(); let mut ctx2 = ScmpFilterContext::new_filter(ScmpAction::Allow).unwrap(); let native_arch = ScmpArch::native().unwrap(); let mut prospective_arch =...
Rust
0
%s'>%s</a></li>\n" % (t['link'], t['title']) forum_content += "</ul>\n" etree.SubElement(forum_page, CONTENT + "encoded").text = etree.CDATA(forum_content) items.append(forum_page) # Generate the final XML document channel = etree.Element("channel") etree.SubElement(channel, WP + "wxr_version").text = "1.2" for item i...
Python
1
>> for &'a mut [T] where T: Copy { fn reshape_mut(self, dim: usize) -> Array1dViewMut<'a, T> { // Assume unit stride. assert!(self.len() >= dim); Array1dViewMut{ buf: self, dim: dim, stride: dim.least_stride(), } } } impl<'a, T> Reshape<'a, (usize, usize), Array2dView<...
Rust
0
# # The Python Imaging Library. # $Id$ # # XBM File handling # # History: # 1995-09-08 fl Created # 1996-11-01 fl Added save support # 1997-07-07 fl Made header parser more tolerant # 1997-07-22 fl Fixed yet another parser bug # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4) # 2001-05-13 fl Ad...
Python
1
{275} -> o '\u{276}', '\u{277}', '\u{278}', '\u{279}', '\u{27a}', '\u{27b}', '\u{27c}', '\u{72}', // \u{27d} -> r '\u{27e}', '\u{27f}', '\u{280}', '\u{281}', '\u{282}', '\u{283}', '\u{284}', '\u{285}', '\u{286}', '\u{287}', '\u{74}', // \u{288} -> t '\u{75}', // \u{289} -> u '\u{28a}', '\u{76}', /...
Rust
0
from fastapi import File, HTTPException, Request, Response, UploadFile, status from src.application import binary as application from src.application.exceptions import ApplicationError from src.domain.services.file_store.minio import MinioStoreDTO from src.presentation.api.v1.arouter import AuthBaseAPIRouter from src....
Python
1
""" Test RAG Agents Script Test the RAG-enhanced agents with sample queries """ import asyncio import logging import sys from pathlib import Path # Add src to path sys.path.append(str(Path(__file__).parent.parent.parent)) from src.rag.rag_agents import RAGCustomerAgent, RAGRestaurantAgent from src.utils.database_con...
Python
1
import random capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix', 'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee', 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Ill...
Python
1
payments' '# periods_semicolon_egg -> compass_airfield_payments' return nonlocal ofppgqfy1r7 global ihr8pk1kfyt pass s89t20fxlha = qn_rmarv4y4 '# periods_semicolon_egg -> compass_airfield_payments' nonlocal ytrrojfby9a @(0j, db5p4ysq37i, 0.0, mdv2g58he3s) @{0 for tiqf16f7slm in t3zcqi9ek...
Python
1
pub(crate) fn debug_dict_pretty(&self, indent_level: u8) -> String { let units = 4; let mut indent = String::new(); for _ in 1..=(indent_level * units) { indent.push(' '); } let mut indent_minus_one = String::new(); for _ in 1..=(indent_level.saturating_sub(1)...
Rust
0
#!/usr/bin/env python import sys, os import time; import re; from datetime import datetime; class ParsingExample: """Application module with several functions to implement and test. """ def parseLogicStr(self, logicStr): """Parse logic string into computable structured format Examples ...
Python
1
const enPicoStringValue_PICO_SV_SAMPLE_PROPERTIES: enPicoStringValue = 52; pub const enPicoStringValue_PICO_SV_SAMPLE_PROPERTIES_PRE_TRIGGER_SAMPLES: enPicoStringValue = 53; pub const enPicoStringValue_PICO_SV_SAMPLE_PROPERTIES_POST_TRIGGER_SAMPLES: enPicoStringValue = 54; pub const enPicoStringValue_PICO_SV_SAMPLE_PR...
Rust
0
image = image::DynamicImage::ImageRgb8(ImageBuffer::from_vec(448, 224, data).unwrap()); let class_be = image.resize_exact(640, 480, image::imageops::FilterType::Triangle).as_bytes() .chunks(3).map(|chunk| u32::from_be_bytes([chunk[0], chunk[1], chunk[2], 0])).collect::<Vec<u32>>(); frame_buffer.copy_fr...
Rust
0
retval OT_ERROR_NO_BUFS Insufficient buffer space to set the Pending Operational Dataset."] #[doc = " @retval OT_ERROR_NOT_IMPLEMENTED The platform does not implement settings functionality."] #[doc = ""] pub fn otDatasetSetPending( aInstance: *mut otInstance, aDataset: *const otOp...
Rust
0
kid_probe_get_value.restype = c_int name = POINTER(c_char_p) data = POINTER(c_char_p) len = POINTER(c_uint64) ret = self.obj.blkid_probe_get_value(pr.ptr, num, name, data, len) return (ret, name, data, len) def probe_lookup_value(self, pr: BlkidProbe, name: str, data: str, len: int) -> int: self.obj.blkid...
Python
1
) - start_circle.center.x()); match start_circle.direction { Direction::Left => theta = delta - theta, Direction::Right => theta += delta, } // Derive the third circle let center = Point::new( start_circle.center.x() + 2.0 * radius * theta.cos(), start_circle.center.y() ...
Rust
0
cxt.0).await?; funs.commit().await?; TardisResp::ok(result) } } use serde::Deserialize; #[derive(Deserialize, Debug)] pub struct School { #[serde(rename="kraOrgNm")] pub name: String, #[serde(rename="engOrgNm")] pub english_name: String, #[serde(rename="orgCode")] pub code: ...
Rust
0
from __future__ import annotations import secrets from typing import Optional from dataclasses import dataclass from asyncpg import Connection from src.app.domain.teams.schemas import Team @dataclass class TeamRepository: """Repository for Team operations using AsyncPG. Note: responsible only for data acc...
Python
1
from django.shortcuts import render # Create your views here. def home(request): return render(request, 'index.html') def add_event_form(request): return render(request, 'add_event_form.html') def add_event_form(request): return render(request, 'add_event_form.html') def engines(request): engines_li...
Python
1
#!/usr/bin/python3 import argparse import os import math import numpy as np import scipy.io.wavfile as wav # ============================================================================== # Constants # SIGNAL_BIT_NB = 16 INDENT = 2*' ' # ============================================================================== #...
Python
1
# You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k. # Define a pair (u, v) which consists of one element from the first array and one element from the second array. # Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums. # Example 1: # Input:...
Python
1
{ pub _min: Vector3<f32>, pub _max: Vector3<f32>, pub _center: Vector3<f32>, pub _size: Vector3<f32>, pub _radius: f32 } impl Default for BoundingBox { fn default() -> BoundingBox { let min = Vector3::new(-1.0, -1.0, -1.0); let max = Vector3::new(1.0, 1.0, 1.0); Boundin...
Rust
0
from util import get_single_letter, get_sb_answers, print_answers, possible_pangram def main(): # title and introduction print("\nWelcome to the \033[1;33;40mSpelling Bee Solver\033[0m! ") print("Based on the NYT's hit game \033[1;33;40mSpelling Bee\033[0m.\n") print("This solver takes one key letter ...
Python
1
from . import download_controllers, shopify_webhook
Python
1
) -> @ast::meta_item { ret @dummy_spanned(ast::meta_word(name)); } fn mk_attr(item: @ast::meta_item) -> ast::attribute { ret dummy_spanned({style: ast::attr_inner, value: *item, is_sugared_doc: false}); } fn mk_sugared_doc_attr(text: ~str, lo: uint, hi: uint) -> ast::attribute { let...
Rust
0
print("Hello") print("Changes!") print("new changes")
Python
1
:from_str(&expected_destination) .map_err(|_| ErrorKind::ParseAddress)?; let destination = decrypted_message.destination.clone(); if destination.public_key != expected_dest.public_key { return Err(ErrorKind::VerifyDestination.into()); } let sender_address = GrinboxAddress::from_str(&self.sender_ad...
Rust
0
8; 4]; for i in 0..c.encode_utf8(&mut buf).len() { unsafe { // SAFETY: The correctness of this code depends on the unescape // iterator always being either at the same place or ahead // of `ptr`. If this ever turns ...
Rust
0
let mut proofs_vdf_post = Vec::with_capacity(post_periods_count); let mut beacon = Beacon::default(); for t in 0..post_periods_count { // Run Beacon let r = beacon.get::<H::Domain>(t); // Generate proof // TODO: avoid cloning let pub...
Rust
0
from easyAI import TwoPlayerGame from easyAI.Player import Human_Player from rich.console import Console from rich.table import Table from easyAI import AI_Player, Negamax class Gomoku(TwoPlayerGame): """ https://www.kurnik.pl/gomoku/zasady.phtml Autorzy: Andrzej Ebertowski s25222 Mateusz Wiśniews...
Python
1
= 380; pub const KEY_SAT: u32 = 381; pub const KEY_SAT2: u32 = 382; pub const KEY_CD: u32 = 383; pub const KEY_TAPE: u32 = 384; pub const KEY_RADIO: u32 = 385; pub const KEY_TUNER: u32 = 386; pub const KEY_PLAYER: u32 = 387; pub const KEY_TEXT: u32 = 388; pub const KEY_DVD: u32 = 389; pub const KEY_AUX: u32 = 390; pub ...
Rust
0
rsIter<Ref: OctetsRef> { name: Option<ParsedDname<Ref>>, answer: Option<RecordIter<Ref, Ptr<ParsedDname<Ref>>>>, } impl<Ref: OctetsRef> Iterator for FoundAddrsIter<Ref> { type Item = ParsedDname<Ref>; #[allow(clippy::while_let_on_iterator)] fn next(&mut self) -> Option<Self::Item> { let na...
Rust
0
hild_r, child_w, *fds = fds s.close() pid = os.fork() if pid == 0: # Child code = 1 try: listener.close() ...
Python
1
elif args[i].lower()=="api": mode.append("api") #noapi elif args[i].replace("noapi","",1).startswith("="): if args[i].split("=")[0].lower()=="noapi": mode.append("noapi") noapis=args[i].split("=")[-1].split(",") parseRes...
Python
1
"""Search query generation for AI expert""" from typing import List, Optional import json import os def get_search_queries() -> List[str]: """Load and return predefined search queries""" queries_path = os.path.join(os.path.dirname(__file__), "data", "search_queries.json") try: with open(queries_pat...
Python
1
crate::Annotation { lang: "ko", tts: Some("핫도그"), keywords: &["소세지", "핫도그"], }, #[cfg(feature = "kok")] crate::Annotation { lang: "kok", tts: Some("हॉट डॉग"), keywords: &[ "फ\u{94d}र\u{901}कफर\u{94d}चर", ...
Rust
0
g sudah diurutkan berdasarkan skor return sorted(candidates, key=lambda x: x['score'], reverse=True) def expand_synonyms(text): tokens = text.split() expanded = [] for token in tokens: expanded.append(token) expanded.extend(get_dynamic_synonyms(token)) return ' '.join(list(set(expan...
Python
1
""" NCL_xy_13.py =============== This script illustrates the following concepts: - Adding error bars on an XY plot See following URLs to see the reproduced NCL plot & script: - Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/xy_13.ncl - Original NCL plots: https://www.ncl.ucar.edu/Applic...
Python
1
c-cfg=armv7m"); println!("cargo:rustc-cfg=armv7em"); } else if target.starts_with("thumbv8m.base") { println!("cargo:rustc-cfg=cortex_m"); println!("cargo:rustc-cfg=armv8m"); println!("cargo:rustc-cfg=armv8m_base"); } else if target.starts_with("thumbv8m.main") { println!...
Rust
0
pin_en(&mut self) -> _SDR_PIN_ENW { _SDR_PIN_ENW { w: self } } #[doc = "Bits 1:2"] #[inline] pub fn spi_flsh_pin_sel(&mut self) -> _SPI_FLSH_PIN_SELW { _SPI_FLSH_PIN_SELW { w: self } } #[doc = "Bit 0"] #[inline] pub fn spi_flsh_pin_en(&mut self) -> _SPI_FLSH_PIN_ENW { ...
Rust
0
nd) # get ref image at the same resolution ref_image = get_resampled_ref_image(reframed_image, product.ref_image) if not ref_image: log.warning( "Cannot do matching correction, no reference image found for image %s", reframed_image.filepath, ...
Python
1
import os from sqlalchemy import create_engine, ForeignKey from sqlalchemy.orm import sessionmaker, DeclarativeBase, Mapped, mapped_column, relationship from typing import List, Optional from dotenv import load_dotenv load_dotenv() DB_URL = os.getenv("DB_URL") if not DB_URL: raise ValueError( "DB_URL envir...
Python
1
from aiogram.types import BotCommand commands = [ BotCommand(command = 'start', description = 'Start the bot'), BotCommand(command = 'menu', description = 'View the main menu'), BotCommand(command = 'help', description = 'View all the available commands'), ] adminIDs = [ 1082846530 ] def display_co...
Python
1
387; pub const rte_eth_input_set_field_RTE_ETH_INPUT_SET_TUNNEL_L4_UDP_KEY: rte_eth_input_set_field = 388; pub const rte_eth_input_set_field_RTE_ETH_INPUT_SET_TUNNEL_GRE_KEY: rte_eth_input_set_field = 389; pub const rte_eth_input_set_field_RTE_ETH_INPUT_SET_FLEX_PAYLOAD_1ST_WORD: rte_eth_input_set_field = 641; ...
Rust
0
pub fn has_screen_keyboard_support() -> bool { unsafe { ll::SDL_HasScreenKeyboardSupport() == 1 } } pub fn is_screen_keyboard_shown(window: &Window) -> bool { unsafe { ll::SDL_IsScreenKeyboardShown(window.raw) == 1 } } <reponame>SubDAO-Network/polkasign-contract #![cfg_attr(not(feature = "std"), no_std)] exte...
Rust
0
pub type UDMACH22BSEL = crate::Reg<u32, _UDMACH22BSEL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _UDMACH22BSEL; #[doc = "`read()` method returns [udmach22bsel::R](udmach22bsel::R) reader structure"] impl crate::Readable for UDMACH22BSEL {} #[doc = "Output Selection for DMA Channel 22 REQ"] pub mod udmach22bsel...
Rust
0
4_i32) as UInt16; (*s).freq = freq as Byte; if freq > 124_i32 as libc::c_uint { self.rescale(); } self.ppmd8_update_model(); } /* H->I changes: ns2indx glue_count, and Glue method BinSum see / EscFreq self.create_successors updates more ...
Rust
0
inout[recon + i - bytewidth] as i16, inout[precon + i] as i16, inout[precon + i - bytewidth] as i16, )); } } else { for i in 0..bytewidth { inout[recon + i] = inout[scanline + i]; } ...
Rust
0
fn print(&self, _fun: &Function, out: &mut dyn Write) { unwrap!(write!(out, "Basic MPPA")); } fn check_type(&self, t: Type) -> Result<(), ir::TypeError> { match t { Type::I(i) | Type::F(i) if i == 32 || i == 64 => Ok(()), Type::I(i) if i == 1 || i == 8 || i == 16 => Ok((...
Rust
0
# Copyright (c) 2019 Eric Steinberger from PokerRL.game._.wrappers._Wrapper import Wrapper class VanillaWrapper(Wrapper): """ This wrapper doesn't track any history in any way and always just shows the current observation. Thus, it does not have perfect recall. This wrapper is suitable for feedforw...
Python
1
()?)?; let child = testdir.spawn_child(&["help"])?; let output = child.wait_with_output()?; let output = output.assert_success()?; // First line haves the version output.stdout_contains(r"zebrad [0-9].[0-9].[0-9]")?; // Make sure we are in help by looking usage string output.stdout_contai...
Rust
0
8], &"\u{00EA}\u{030C}"); decode_big5(&[0x88u8, 0xA7u8], &"\u{00EA}"); decode_big5(&[0x99u8, 0xD4u8], &"\u{8991}"); decode_big5(&[0x99u8, 0xD5u8], &"\u{27967}"); decode_big5(&[0x99u8, 0xD6u8], &"\u{8A29}"); // Edge cases surrounded with ASCII decode_big5( &[0...
Rust
0
days readmission_label = 1 if time_diff < time_window else 0 conditions = visit.get_code_list(table="diagnoses_icd") procedures = visit.get_code_list(table="procedures_icd") drugs = visit.get_code_list(table="prescriptions") # exclude: visits without condition, procedure, or dru...
Python
1
rse_food() { let expected = Food { ingredients: vec!["mxmxvkd", "kfcds", "sqjhc", "nhms"].iter().map(|&s| s.to_owned()).collect(), allergens: vec!["dairy", "fish"].iter().map(|&s| s.to_owned()).collect(), }; assert_eq!(Ok(expected), "mxmxvkd kfcds sqjhc nhms (contains da...
Rust
0
nemonic = Mnemonic::from_entropy(entropy, Language::English).unwrap(); assert_eq!(format!("{:x}", mnemonic), "33e46bb13a746ea41cdde45c90846a79"); assert_eq!(format!("{:X}", mnemonic), "33E46BB13A746EA41CDDE45C90846A79"); assert_eq!(format!("{:#x}", mnemonic), "0x33e46bb13a746ea41cdde45c90846a79...
Rust
0
epr(file_no).zfill(6)+'.h5' #print(filename1) #print(filename2) phase_space=np.abs(osh5io.read_h5(filename5)) # print(repr(phase_space)) eden=osh5io.read_h5(filename2) ex = osh5io.read_h5(filename3) ey = osh5io.read_h5(filename4) # p1x1=np.abs(osh5io.rea...
Python
1
::min(bytes.len() / Self::WORD_SIZE, N); let mut ret = Self::new(); // FixedUInt::<T, N>::new(); for word in 0..iter { let mut v = T::zero(); let mut next = T::zero(); for i in 0..Self::WORD_SIZE { let byte = bytes[word * Self::WORD_SIZE + (Self::WORD_...
Rust
0
#[doc(alias = "gsk_linear_gradient_node_new")] pub fn new( bounds: &graphene::Rect, start: &graphene::Point, end: &graphene::Point, color_stops: &[ColorStop], ) -> LinearGradientNode { assert_initialized_main_thread!(); let n_color_stops = color_stops.len() as usi...
Rust
0
type EpochsPerEth1VotingPeriod: Unsigned + Clone + Sync + Send + Debug + PartialEq; type SlotsPerHistoricalRoot: Unsigned + Clone + Sync + Send + Debug + PartialEq; /* * State list lengths */ type EpochsPerHistoricalVector: Unsigned + Clone + Sync + Send + Debug + PartialEq; type EpochsPe...
Rust
0
ct.GooseUser.html) //! threads during a load test is written to this log file. //! //! ## Debug File logger //! The Goose debug logger is enabled with the `--debug-log` command-line option, or the //! [`GooseDefault::DebugLog`](../config/enum.GooseDefault.html#variant.DebugLog) default //! configuration option. //! //!...
Rust
0
; pub use self::nearest_neighbour_gridding::NearestNeighbourGridding; pub use self::patch_orientation::PatchOrientation; pub use self::percent_equal_to::PercentEqualTo; pub use self::percent_greater_than::PercentGreaterThan; pub use self::percent_less_than::PercentLessThan; pub use self::perimeter_area_ratio::Perimeter...
Rust
0
.with_append(STR_SLICE_2) .with_append(STR_SLICE_3) .with_append(STR_SLICE_4) .with_append(STR_SLICE_3) .with_append(STR_SLICE_5) .build(), ); Console::write_line( FeStringBuilder::new() .with_append(STR_SLICE_2) ...
Rust
0
JsonGetPath => f.write_str("#>"), Token::JsonGetPathAsText => f.write_str("#>>"), Token::JsonContainsJson => f.write_str("@>"), Token::JsonContainedInJson => f.write_str("<@"), Token::JsonContainsField => f.write_str("?"), Token::JsonContainsAnyFields => f.wri...
Rust
0
"d20: {}", d20); } } <reponame>Wandalen/RustPractice<filename>all/macro_declarative_concat_paste/src/bin/simple.rs use paste::paste; /* macro of concatenation to synth an identifier using module::paste */ macro_rules! hi { ( $id : tt ) => { paste!( [< hi_ $id >] )( stringify!( $id ) ); } } // fn main...
Rust
0