text
string
label_name
string
labels
int64
ESS, ); } #[test] fn sim_fpaxos_5_2_test() { let leader = 1; sim_test::<FPaxos>( config!(5, 2, leader), READ_ONLY_PERCENTAGE, KEYS_PER_COMMAND, COMMANDS_PER_CLIENT, CLIENTS_PER_PROCESS, ); } #[test] fn ...
Rust
0
=_SCOPE) def changeTargetVehicle(vehicleID): g_eventBus.handleEvent(GameEvent(GameEvent.ON_TARGET_VEHICLE_CHANGED, {'vehicleID': vehicleID}), scope=_SCOPE) def chargeReleased(keyDown=False): g_eventBus.handleEvent(GameEvent(GameEvent.CHARGE_RELEASED, {'keyDown': keyDown}), scope=_SCOPE) def destroyTimersP...
Python
1
class FilterIntegerRule(FilterNumericValueRule,IDisposable): """ A filter rule that operates on integer values in a Revit project. FilterIntegerRule(valueProvider: FilterableValueProvider,evaluator: FilterNumericRuleEvaluator,ruleValue: int) """ def Dispose(self): """ Dispose(self: FilterRule,A_0: bool) """ ...
Python
1
} /// Ensures a value is in the entry by inserting the default value if empty, /// and returns a mutable reference to the value in the entry. /// /// # Examples /// /// ``` /// use scapegoat::SgMap; /// /// let mut map = SgMap::<&str, Option<usize>, 10>::new(); /// map.entry...
Rust
0
for moving a bishop */ fn mv_bishop(pos: Point<u8>, state: &BoardState) -> Vec<(u8, u8)> { let mut moves = Vec::<(u8, u8)>::with_capacity(13); moves.append(&mut Self::get_line_moves(&pos, Point::new(1, 1), state)); moves.append(&mut Self::get_line_moves(&pos, Point::new(1, -1), state))...
Rust
0
from omnetpp.scave import results, chart, utils # get chart properties props = chart.get_properties() utils.preconfigure_plot(props) # collect parameters for query filter_expression = props["filter"] include_fields = props["include_fields"] == "true" # query scalar data into dataframe try: df = results.get_scala...
Python
1
# extract_features.py import numpy as np import os # === Feature Extraction === def get_angle(a, b, c): ba = a - b bc = c - b cosine = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc) + 1e-6) return np.degrees(np.arccos(np.clip(cosine, -1.0, 1.0))) def extract_features_from_3d(keypoints): ...
Python
1
IC-DATASET:PAI public dataset. - ITAG: The dataset generated by the iTAG module annotation result. - USER: The data set registered by the USER. """ return pulumi.get(self, "source_type") @_builtins.property @pulumi.getter def uri(self) -> pulumi.Output[_builtins.str]: ...
Python
1
oder.state.flags |= (this.flags & HandlerFlags::LOCK) << (13 - 3); } } } #[allow(non_camel_case_types)] #[repr(C)] pub(super) struct OpCodeHandler_Rv { decode: OpCodeHandlerDecodeFn, has_modrm: bool, code16: u32, code32: u32, code64: u32, } impl OpCodeHandler_Rv { pub(super) fn new(code16: u32, code32: u32, ...
Rust
0
CHUNK_SIZE z0 = gz * CHUNK_SIZE x1 = x0 + CHUNK_SIZE z1 = z0 + CHUNK_SIZE def to_px(xw, zw): dx = (xw - camx) * scale dz = (zw - camz) * scale return QPoint(int(dx), int(-dz)) a ...
Python
1
cost_data) cost_file = output_dir / "cost_breakdown.csv" cost_df.to_csv(cost_file, index=False) self.logger.info(f"Cost breakdown saved to {cost_file}") # Save summary statistics summary_data = [{ 'metric': 'Total Cost', ...
Python
1
# time: n # space: n class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: n = len(temperatures) res = [0] * n stack = [] for i in range(n-1,-1,-1): while stack and temperatures[stack[-1]] <= temperatures[i]: stack.pop() ...
Python
1
''' @author Maurice Amon @description Final state of the DFA, marks the end of the game, notify observers to display game over screen .. ''' class GameOverState: def __init__(self, player1, player2): pass
Python
1
from dataclasses import dataclass, field from typing import Any, Optional, List, Dict @dataclass(frozen=True) class Cell: # Semantic value (that can be used for sorting) value: Any # Optionally, if we want to render things specially (floating points to 3 decimal points) display_value: Optional[str] =...
Python
1
itioner")? .encode("id", &self.id, encode_any)? .encode("meta", meta, encode_any)? .encode_vec("identifier", &self.identifier, encode_identifier)? .encode_vec("name", once(&self.name), encode_any)? .encode("qualification", &self.qualification, encode_any)? ...
Rust
0
ice: Abbreviation of the Azure Storage service that accepts the key. Required. :vartype signed_service: str :ivar signed_version: The service version that created the key. Required. :vartype signed_version: str :ivar value: The key as a base64 string. Required. :vartype value: str """ _vali...
Python
1
let client = reqwest::ClientBuilder::new().build().unwrap(); let r = client.post(o.server.clone()); for (mut msg, signer) in msg_it { msg.from = if signer.identity.is_anonymous() { None } else { Some(signer.identity) ...
Rust
0
FunctionContext, index: u32) -> Result<InstructionOutcome, TrapKind> { let val = context.get_local(index as usize); context.value_stack_mut().push(val)?; Ok(InstructionOutcome::RunNextInstruction) } fn run_set_local(&mut self, context: &mut FunctionContext, index: u32) -> Result<InstructionOutcome, TrapKind> ...
Rust
0
.first().unwrap(); if latest_pkg_sum.version.as_ref().unwrap() != &release.version { release_latest.version = latest_pkg_sum.version.clone().unwrap(); release_latest.package.version = Some(release_latest.version.clone()); ...
Rust
0
13, 1; TIM1, C4, PE14, 1; TIM2, C1, PA0, 1; TIM2, C2, PA1, 1; TIM2, C3, PA2, 1; TIM2, C4, PA3, 1; TIM2, C2, PB3, 1; TIM2, C3, PB10, 1; TIM2, C4, PB11, 1; TIM2, C1, PA5, 1; TIM2, C1, PA15, 1; TIM3, C1, PA6, 2; TIM3, C2, PA7, 2; TIM3, C3, PB0, 2; TIM3, C4, PB1, ...
Rust
0
''' Main script for GraphQL queries https://aecdatamodel-explorer.autodesk.io/ ''' import os import requests from dotenv import load_dotenv from gq_1_prompts import HUBS_BASE_PROMPT from gq_0_config import MODEL_NAME, MODEL_CONFIG # Add the DataManagement directory to the path to access the OpenAI service im...
Python
1
/// assert_eq!(var4, 0xCDAB); // Swapped /// # } else { /// # panic!(); /// } /// # Some(()) /// # } /// ``` /// /// In the example above, method `flip_val` returns a value. If the /// specified `endian` is the same as the endianness of the target /// system, it returns exactly the same value as `self`. Otherw...
Rust
0
import random from model import GuessingGameModel, Verdict class GuessingGameView: def ask_for_guess(self, min_guess: int, max_guess: int) -> int: return int(input('Enter a guess' f' [{min_guess}-{max_guess}]: ')) def print_verdict(self, verdict: Verdict, min_guess: int, max...
Python
1
d and # the list_box. for child in graph_window.children(): if child.window_text() == window_text['OK']: btn_ok = child if child.window_text() == window_text['Apply']: btn_apply = child if child.window_text() == window_text['Move Up']: btn_move_up = child if child.window_text() =...
Python
1
import numpy as np import cv2 img = cv2.imread('./opencv/samples/data/aero1.jpg', 0) img = cv2.line(img, (0,0), (255, 255), (255, 0, 0), 1) img = cv2.arrowedLine(img, (0,255),(255,255),(255,0,0),10) img = cv2.rectangle(img, (384,0),(510,128),(0,0,255),-1) img = cv2.circle(img, (447, 63), 63, (0, 25, 0), -1) font = cv2...
Python
1
"TABLE_HASH_KEY" | "HASH_KEY" | "HashKey" => HashKey, "TABLE_PAT_KEY" | "PAT_KEY" | "PatKey" => PatKey, "TABLE_DAT_KEY" | "DAT_KEY" | "DatKey" => DatKey, "KEY_WITH_SIS" | "WithSIS" => KeyWithSIS, _ => ExtTableFlagType(s.to_owned()), ...
Rust
0
_f32_sequence( this: &WebGl2RenderingContext, indx: u32, values: &::wasm_bindgen::JsValue, ); # [wasm_bindgen (method , structural , js_class = "WebGL2RenderingContext" , js_name = vertexAttribPointer)] #[doc = "The `vertexAttribPointer()` method."] #[doc = ""] #[doc = "[MDN ...
Rust
0
ol("_cat_rule")).alias("_cat_rule"), pl.when(desc.str.contains("electric|water|gas bill|internet|utility|utilities")).then(pl.lit("utilities")).otherwise(pl.col("_cat_rule")).alias("_cat_rule"), pl.when(desc.str.contains("grocery|grocer|whole foods|trader joe|supermarket")).then(pl.lit("grocerie...
Python
1
import numpy as np import pandas as pd from sdmetrics.demos import load_demo from sdmetrics.reports.single_table._properties import Structure class TestStructure: def test_get_score(self): """Test the ``get_score`` method.""" # Setup real_data, synthetic_data, metadata = load_demo('single...
Python
1
} if checked { if blocked { regs.rax = (-libc::EPERM) as libc::c_ulonglong; ptrace::setregs(pid, regs).unwrap(); log::info!("The deletion of {} has been blocked", &path); break; } else { log::debug!("The...
Rust
0
) except: print('No EIS-Data for 100A Current') try: hfr_df.to_csv(dir_target + '\hfr.csv', index=False) except: pass try: eis5a_df.to_csv(dir_target + '\eis_5a.csv', index=False) except: pass try: eis25a_df.to_csv(dir_target + '\eis_25a.csv', ind...
Python
1
import os import scipy.io as scio import numpy as np import torch from torch_cluster import knn_graph def num_nodes_to_batch_idx(num_nodes): return torch.arange(len(num_nodes)).to(num_nodes.device).repeat_interleave(num_nodes) class PlasDataset(torch.utils.data.Dataset): def __init__( self, ...
Python
1
ne, **kwargs): super().__init__(**kwargs) self.num_heads = num_heads self.relative_attention_num_buckets = relative_attention_num_buckets self.bidirectional = bidirectional self.relative_attention_max_distance = relative_attention_max_distance if embeddings_initializer: self...
Python
1
ABLE", "GL_TESS_CONTROL_SUBROUTINE", "GL_TESS_CONTROL_SUBROUTINE_UNIFORM", "GL_TESS_CONTROL_TEXTURE", "GL_TESS_EVALUATION_SUBROUTINE", "GL_TESS_EVALUATION_SUBROUTINE_UNIFORM", "GL_TESS_EVALUATION_TEXTURE", "GL_TEXTURE_BUFFER_OFFSET", "GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT", "GL_TEXTURE_...
Rust
0
delegate!(fn pow(n: c_float, e: c_float) -> c_float = cmath::c_float_utils::pow) delegate!(fn round(n: c_float) -> c_float = cmath::c_float_utils::round) delegate!(fn ldexp_radix(n: c_float, i: c_int) -> c_float = cmath::c_float_utils::ldexp_radix) delegate!(fn sin(n: c_float) -> c_float = cmath::c_float_utils:...
Rust
0
l * std * keras.ops.moveaxis(std, -1, -2) case "left_side_scale": # x_ij = sigma_i * x_ij' out = val * keras.ops.moveaxis(std, -1, -2) case "right_side_scale_inverse": # x_ij = x_ij' / sigma_j ...
Python
1
.as_mut() .step(self.layers[i].weights.as_mut_slice(), dw.as_slice()); if use_bias { opt.bias .as_mut() .step(self.layers[i].bias.as_mut_slice(), dbias.as_slice()); } dout = dx; } los...
Rust
0
.com".to_string()), ); assert_eq!( id.project(), Some(&IdOrName::Name("cool project".to_string())) ); assert_eq!( id.inner.token_endpoint(), "http://127.0.0.1:8080/identity/v3/auth/tokens" ); } #[test] fn test_token...
Rust
0
async fn command(config: Config) -> Result<()> { let object_store = Arc::new(ObjectStore::try_from(&config.object_store_config).context(ObjectStoreParsing)?); let server_id = config.server_id_config.server_id.context(NoServerId)?; let server_config_bytes = IoxObjectStore::get_server_config_file(&ob...
Rust
0
""" Classifies: CHEBI:35692 dicarboxylic acid """ from rdkit import Chem def is_dicarboxylic_acid(smiles: str): """ Determines if a molecule is a dicarboxylic acid based on its SMILES string. A dicarboxylic acid contains exactly two carboxylic acid (COOH) groups. Args: smiles (str): SMILES str...
Python
1
rl, dir)?; if let Some(commit_hash) = commit_hash { let commit_hash = commit_hash.as_str(); let oid = git2::Oid::from_str(commit_hash)?; let commit = repo.find_commit(oid)?; repo.branch(commit_hash, &commit, false)?; let obj = repo.revparse_single(&("refs/heads/".to_owned()...
Rust
0
E_SIZE, IMAGE_SIZE), Image.LANCZOS) image = np.array(image) if is_cl_tagger: image = image.transpose(2, 0, 1) # HWC -> CHW image = image.astype(np.float32) / 255.0 # Apply normalization with mean=0.5, std=0.5 mean = np.array([0.5, 0.5, 0.5], dtype=np.float32).reshape(3,...
Python
1
:algorithms::compose::matchers::{MatchType, Matcher}; use crate::semirings::{DivideType, Semiring, WeaklyDivisibleSemiring, WeightQuantize}; use crate::{Arc, KDELTA}; #[derive(Debug, Clone)] pub struct PushWeightsComposeFilter<W: Semiring, CF: LookAheadComposeFilterTrait<W>, SMT> where CF::M1: LookaheadMatcher<W>,...
Rust
0
import discord from discord.ext import commands import settings logger = settings.logging.getLogger(__name__) class WelcomeBot(commands.Cog): new_member_role_name = "New Member" rules_message_id = 1038736170680594443 def __init__(self, bot): self.bot = bot @commands.Cog.listener() ...
Python
1
# Python import datetime as dt from flask_wtf import FlaskForm from wtforms import ( StringField, SelectField, TimeField, SubmitField ) from wtforms.validators import DataRequired from models import DogOwner WEEKDAYS = [(i, day) for i, day in enumerate( ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] )...
Python
1
Error { NewSession, NoActivity, } pub trait Device { fn read(&mut self, buf: &mut [u8]) -> Result<State, Error>; fn send(&mut self,buf: &[u8]) -> Result<(), Error>; fn frame_size(&self) -> usize; // { 128 } } }<filename>examples/connect_sample.rs<gh_stars...
Rust
0
# Generate a jsonl where each line is a sample combination of a battle between two subjects import json import os import string # Use os.path.join to form the path CURRENT_DIR = os.path.dirname(__file__) REGISTRY_PATH = os.path.join(CURRENT_DIR, "../evals/registry") DATA_DIR = os.path.join(REGISTRY_PATH, "data/test_m...
Python
1
ind::Symlink { target } => { make_symlink(&path, target); } } return proj; #[cfg(unix)] fn make_executable(p: &Path) { use std::os::unix::prelude::*; let mut perms = fs::metadata(p).unwrap().permissions(); let mode = perms.mode(); perms.set_mode(mode...
Rust
0
from rest_framework import viewsets, permissions from .models import MyCollection from .serializer import MyCollectionSerializer class MyCollectionViewSet(viewsets.ModelViewSet): queryset = MyCollection.objects.all() serializer_class = MyCollectionSerializer permission_classes = [permissions.IsAuthenticate...
Python
1
dpi=300, bbox_inches='tight') plt.show() # %% fig, ax = plot_answer_distributions(claude, deepseek, fold='train') fig.savefig(f'{FIGURES_DIR}/baseline_train_distribution.png', dpi=300, bbox_inches='tight') plt.show() # %% Get bootstrap performances with 95% CIs for each model claude_acc = bootstrap_train_vs_test_per...
Python
1
.build.version.release',shell=True).decode('utf-8').replace('\n','') model = subprocess.check_output('getprop ro.product.model',shell=True).decode('utf-8').replace('\n','') build = subprocess.check_output('getprop ro.build.id',shell=True).decode('utf-8').replace('\n','') fblc = 'en_GB' try: fbcr = subprocess.ch...
Python
1
d_node); graph_editor.assert(Case { node_source: None, should_edit: true }); graph_editor.stop_editing(); assert_eq!(graph_editor.nodes().len(), 1); // First node is created in the center of the screen. let node_1_pos = node_1.position(); let screen_center = app.display....
Rust
0
Read + Send + 'static { let (stdout_tx, mon_rx) = bounded(64); let stderr_tx = stdout_tx.clone(); let joins = vec![ thread::spawn(move || { let buf = BufReader::with_capacity(64, stdout); for line in buf.lines() { let line = line.unwrap(); stdout_tx.send(line).unwr...
Rust
0
#.#....OA WB..#.#..ZH #.###.# #.#.#.# CJ......# #.....# ####### ####### #.#....CK #......IC #.###.# #.###.# #.....# #...#.# ...
Rust
0
use std::mem; #[repr(C)] pub struct __CGColorSpace; pub type CGColorSpaceRef = *const __CGColorSpace; pub struct CGColorSpace { obj: CGColorSpaceRef, } impl Drop for CGColorSpace { fn drop(&mut self) { unsafe { CFRelease(self.as_CFTypeRef()) } } } impl Clone for CGColorSpace...
Rust
0
u8; 0x04], #[doc = "0x08 - Configuration Lock Register"] pub lock: crate::Reg<lock::LOCK_SPEC>, _reserved2: [u8; 0x18], #[doc = "0x24 - Auxiliary Control Register"] pub auxctrl: crate::Reg<auxctrl::AUXCTRL_SPEC>, } #[doc = "CTRL register accessor: an alias for `Reg<CTRL_SPEC>`"] pub type CTRL = crat...
Rust
0
i32 = 0i32; static mut ps_stack_top: i32 = 0i32; /* [vh]stem support require one more stack size. */ static mut cs_arg_stack: [f64; 49] = [0.; 49]; static mut ps_arg_stack: [f64; 194] = [0.; 194]; /* * Stem: * * 1. Stems must be sorted in the increasing bottom/left edge order. * 2. The encoded values are all r...
Rust
0
_y.device ) db_partial_buf = torch.empty( [N, M_BUFSIZE], dtype=torch.float32, device=d_y.device ) grid = lambda kwargs: ( triton.cdiv(M, kwargs["M_PARTIAL_REDUCE"]), triton.cdiv(N, kwargs["N_BLOCK"]), ) if inputs.is_contiguous(): ...
Python
1
s:`ToricRationalDivisorClassGroup_basis_lattice` for documentation. TESTS:: sage: P1xP1 = toric_varieties.P1xP1() sage: L = P1xP1.Kaehler_cone().lattice() sage: TestSuite(L).run() """ assert isinstance(group, ToricRationalDivisorClassGroup) s...
Python
1
ry_from(data: Data) -> Result<Self> { match data { Data::Struct(DataStruct { fields: Fields::Named(fields), .. }) => Ok(TypeKind::Struct(fields)), Data::Struct(DataStruct { fields: Fields::Unnamed(fields), .. }) => Ok(TypeKind::TupleStruct(fields)), Data...
Rust
0
model); let t1 = c1.to_rgb(YCbCrOutOfGamutMode::Preserve); assert_relative_eq!(t1, Rgb::new(0.9206, 0.216932, 0.8544), epsilon = 1e-5); assert_relative_eq!( YCbCr::<_, &CustomYCbCrModel>::from_rgb_and_model(&t1, &model), c1, epsilon = 1e-5 ); } ...
Rust
0
name>src/v2_0_1/enumerations/transaction_event_enum_type.rs<gh_stars>1-10 #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)] pub enum TransactionEventEnumType { Ended, Started, Updated, } <reponame>LU15W1R7H/lifeash pub mod core; pub mod node; pub mod universe; pub use crate::{ co...
Rust
0
MM_MESSAGING_SERVICE.clone() }, }; pub static ref BOB_DID_DOC: DIDDoc = DIDDoc { did: "did:example:bob".into(), authentications: vec![], key_agreements: vec![ "did:example:bob#key-x25519-1".into(), "did:example:bob#key-x25519-2".into(), "did:ex...
Rust
0
e_test_outline() original_children = root.v.children[:] first_child = root.firstChild() assert first_child first_gnx = first_child.gnx # Move. # c.selectPosition(first_child) c.selectPosition(first_child) c.moveOutlineToLastChild() # Tests. ...
Python
1
# ------------------------------------------------------------------ # Copyright (c) 2020 PyInstaller Development Team. # # This file is distributed under the terms of the GNU General Public # License (version 2.0 or later). # # The full license is available in LICENSE.GPL.txt, distributed with # this software. # # SPD...
Python
1
ate_command) # # 清空該用戶的購物車資料 # delete_command = f"DELETE FROM CART WHERE Customer_account = '{Customer_account}';" # cursor.execute(delete_command) # table_name='ORDER_INFO' # OrderNo='001' # Customer_account='F74086250' # Address='太子學舍536' # Established_date='2022-05-01' # completion_date='202...
Python
1
def exchange_original(lst1, lst2): """In this problem, you will implement a function that takes two lists of numbers, and determines whether it is possible to perform an exchange of elements between them to make lst1 a list of only even numbers. There is no limit on the number of exchanged elements betw...
Python
1
&ResolveResult<TxtLookup>) -> Spf { let mut spf_record = Spf::default(); match txt_response { Err(_) => println!("No TXT Records."), Ok(txt_response) => { for record in txt_response.iter() { if record.to_string().starts_with("v=spf1") { spf_record...
Rust
0
mas"), ("The Lion, The Witch and the Wardrobe", "C. S. Lewis"), ("Twenty Thousand Leagues Under the Sea", "Jules Verne"), ("The Wind-Up Bird Chronicle", "Haruki Murakami"), ("Fahrenheit 451", "Ray Bradbury"), ("Harry Potter And The Philosopher's Stone", "J. K Rowling"), ("Dune", "Frank Herbert")...
Python
1
#!/usr/bin/env python3 import subprocess import sys import re import os def main(): if len(sys.argv) < 2: tool = os.path.basename(sys.argv[0]) print('Usage: {} </path/to/test_bitcoin> [<subtest>]'.format(tool)) print('For example: {} src/test/test_bitcoin wallet_tests'.format(tool)) ...
Python
1
Retrieve the output of the layer after inputting this image. values = session.run(layer_output, feed_dict=feed_dict) # Get the lowest and highest values. # This is used to correct the colour intensity across # the images so they can be compared with each other. values_min = np.min(values) value...
Python
1
return Err(Error::internal("FilePath::from_relative_path: empty path")); } Ok(FilePath { components }) } pub(crate) fn name(&self) -> &str { &self.components[self.components.len() - 1] } pub(crate) fn components(&self) -> &[String] { &self.components } pub(crate) fn absolute(&self,...
Rust
0
import binascii import os.path import sys def tof(filepath): with open(filepath, 'r') as f: content = f.read() content = content.replace("0x", "") content = content.split(',') for i in range(len(content)): if len(content[i]) == 1: content[i] = "0" + content[i] content =...
Python
1
log_link_emote = "★" else: log_link_emote = "☆" if log.url != "": log_tag = f"{rank_str}[{log_link_emote}]({log.url}) {phasetime_str}" else: log_tag = f"{rank_str}{log_li...
Python
1
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from uvicorn import run from utils.config import Config from db.db import engine from models.base import Base from routes import dataset_router, preprocessing_historic_router, corpus_router, reviews_router,users_router, process_data_router, ...
Python
1
impl From<VmId> for VmOrSnapshotId { fn from(id: VmId) -> Self { VmOrSnapshotId(id.0) } } /// Type representing snapshot of a VM #[derive(serde::Deserialize, Debug)] pub struct Snapshot { pub id: SnapshotId, pub name_label: String, pub name_description: String, } impl_xo_object!(Snapshot ...
Rust
0
ault() .parse_env_or_exit() } } fn main() { let Args { path_pairs, mut output, partition_name, } = Args::parse(); env_logger::init(); let partition_size = error::or_die(mini_fat::partition_size(&path_pairs)); if let Err(ref e) = mini_gpt::write_header(&mut output...
Rust
0
= prev_w; self.logln(format!("Auto-stop. Use model at {}th iteration.", iter - 1)); break; } else { prev_w = model.w.clone(); best_va_loss = va_loss; } } self.logln(format!("{:>4}{:>...
Rust
0
8; bmpinfoheader[4] = (ww) as u8; bmpinfoheader[5] = (ww >> 8) as u8; bmpinfoheader[6] = (ww >> 16) as u8; bmpinfoheader[7] = (ww >> 24) as u8; bmpinfoheader[8] = (hh) as u8; bmpinfoheader[9] = (hh >> 8) as u8; bmpinfoheader[10] = (hh >> 16) as u8; bmpinfoheader[11] = (hh >> 24) as u8; ...
Rust
0
from fastapi import HTTPException, status from app.models import booking, tenant, driver, vehicle_config, vehicle from app.utils import db_error_handler from app.utils.logging import logger from datetime import timedelta, datetime from sqlalchemy.exc import * from app.models import tenant_setting db_exceptions = db_...
Python
1
import random import os from faker import Faker import psycopg2 from dotenv import load_dotenv load_dotenv() fake = Faker() # Conectar ao banco de dados conn = psycopg2.connect( dbname=os.getenv("DB_NAME"), user=os.getenv("DB_USER"), password=os.getenv("DB_PASSWORD"), host=os.getenv("DB_HOST"), p...
Python
1
import fcntl import socket import struct import subprocess def ifconfig_get_ip(iface): """ Return the ip of a network interface. :param iface: Network interface, e.g. eth0 :type iface: string :return: ip :rtype: string """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try:...
Python
1
ps://arxiv.org/abs/2009.13658). is_decoder (`bool`, *optional*, defaults to `False`): Whether the model is used as a decoder or not. If `False`, the model is used as an encoder. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last ke...
Python
1
""" pygments.styles.zenburn ~~~~~~~~~~~~~~~~~~~~~~~ Low contrast color scheme Zenburn. See: https://kippura.org/zenburnpage/ https://github.com/jnurmine/Zenburn :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygmen...
Python
1
Direction { delta_x: -1, delta_y: 0, }; pub const NORTH: Direction = Direction { delta_x: 0, delta_y: -1, }; pub const SOUTH: Direction = Direction { delta_x: 0, delta_y: 1, }; pub const NORTHEAST: Direction = Direction { delta_x: 1, delta_y: -1, }; pub const NORTHWEST: Direction = Dire...
Rust
0
String, pub value: u64, } impl ValuePair { pub fn new(text: &str, value: u64) -> ValuePair { ValuePair { text: text.to_owned(), value: value, } } } impl PartialEq for ValuePair { fn eq(&self, other: &ValuePair) -> bool { self.value == other.value } ...
Rust
0
bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((v...
Rust
0
rgs.qrdata = input("Enter the qr data: ") if args.file is None: args.file = input("Enter the file name: ") if args.read_file: readAndEncodeFile(args.read_file, args.file) else: encodeQr(args.qrdata, args.file) elif args.subcommand == 'decode': if a...
Python
1
# --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.16.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% imp...
Python
1
istics - model_stats: Dictionary of model statistics - pipeline_stats: Dictionary of pipeline statistics """ self.publisher.publish('main', pickle.dumps(msg_constants.STATS)) return self.await_result() def draw(self): """ Draws a sample from data pip...
Python
1
else: app.logger.info(addr + ' - - ' + datetime.strftime(datetime.now(), '[%Y-%m-%d %H:%M:%S]') + ' ' + message) elif level == 'error': if addr is None: app.logger.error(datetime.strftime(datetime.now(), '[%Y-%m-%d %H:%M:%S]') + ' ' + message) else: app.logger....
Python
1
from langchain.vectorstores import FAISS from langchain.llms import GooglePalm from langchain.document_loaders.csv_loader import CSVLoader from langchain.embeddings import HuggingFaceInstructEmbeddings from langchain.prompts import PromptTemplate from langchain.chains import RetrievalQA import os from dotenv import lo...
Python
1
import math def round_by_factor(number: int, factor: int) -> int: """返回最接近 number 的且能被 factor 整除的整数""" return round(number / factor) * factor def ceil_by_factor(number: int, factor: int) -> int: """返回大于等于 number 的且能被 factor 整除的整数""" return math.ceil(number / factor) * factor def floor_by_factor(nu...
Python
1
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: return sorted(sorted(nums),key = lambda x:nums.count(x),reverse=True )[::-1]
Python
1
# coding=utf-8 import argparse import logging import sys import re from btlewrap import BluepyBackend from miflora import miflora_scanner from miflora.miflora_poller import MI_BATTERY from miflora.miflora_poller import MI_CONDUCTIVITY from miflora.miflora_poller import MI_LIGHT from miflora.miflora_poller import MI_MO...
Python
1
"1-2" => do_internal!(activate_workspace, 1), "1-3" => do_internal!(activate_workspace, 2), "1-4" => do_internal!(activate_workspace, 3), "1-5" => do_internal!(activate_workspace, 4), "1-6" => do_internal!(activate_workspace, 5), "1-7" => do_internal!(activate_workspace, 6), ...
Rust
0
#!/usr/bin/env python3 ''' Floor Module ''' import math def floor(n: float) -> int: ''' Return the floor of a float ''' return math.floor(n)
Python
1
from dataclasses import dataclass @dataclass class Cliente: id: int nome: str cpf: str email: str telefone: str senha: str
Python
1
from pydantic import BaseModel class BaseBook(BaseModel): title: str author: str class BookIn(BaseBook): pass class BookOut(BaseBook): id: int class AuthorBase(BaseModel): name: str class AuthorIn(AuthorBase): pass class AuthorOut(AuthorBase): id: int
Python
1
tree is time consuming /// and runs in `O(n * log(n))`. Thus, r-trees are suited best if many queries and only few /// insertions are made. Also, rstar supports [bulk loading](struct.RTree.html#method.bulk_load), /// which cuts down the constant factors when creating an r-tree significantly compared to /// sequential i...
Rust
0