text
string
label_name
string
labels
int64
#!C:/Python37-32/python # -*- coding: UTF-8 -*- import json import os import platform from typing import Tuple import unittest from bs4 import BeautifulSoup from PixivBrowserFactory import PixivBrowser import PixivConfig import PixivConstant import PixivHelper from PixivArtist import PixivArtist from PixivImage impo...
Python
1
import requests from config import Config class BNYMellonAPI: def __init__(self): self.headers = { "Authorization": f"Bearer {Config.BNY_MELLON_API_KEY}", "Content-Type": "application/json" } def get_account_balance(self, account_id): url = f"{Config.BNY_MELLON_...
Python
1
import numpy as np from haul_quantum.sim.noise import NoiseModel from haul_quantum.sim.statevector import StatevectorSimulator def test_noise_preserves_norm(): sim = StatevectorSimulator(1) clean = sim.zero_state() nm = NoiseModel(1, seed=123) for channel in ("bit_flip", "phase_flip", "depolarizing")...
Python
1
# coding: utf-8 """ Corbado Backend API # Introduction This documentation gives an overview of all Corbado Backend API calls to implement passwordless authentication with Passkeys. The version of the OpenAPI document: 2.0.0 Contact: support@corbado.com Generated by OpenAPI Generator (https://ope...
Python
1
refixes can be rooted by root_path, // we exit the loop. if *qualifier == root_path { break; } else { path_prefix = qualifier; } } else { // If path_prefix ...
Rust
0
_indices::Config for Runtime { type AccountIndex = AccountIndex; type Currency = Balances; type Deposit = IndexDeposit; type Event = Event; type WeightInfo = (); } parameter_types! { pub const ExistentialDeposit: Balance = 1 * COASE; // For weight estimation, we assume that the most locks o...
Rust
0
15, 33, 13, 35, 33, 19, 1, 23, 43, 46, 1, 43, 35, 1, 43, 11, 21, 1, 33]}, {"tokens": ['I', 't', "'", 's', '▁', 'o', 'k', 'a', 'y'], "label": [24, 46, 2, 43, 1, 35, 27, 7, 56]} ] symbol_table = {} with open(symbol_table_path, 'r') as f: lines = f.r...
Python
1
_query"]: print("💬 ユーザークエリ : ", state["history"]) if len(state["history"]) == 1: context = state["history"][0]["role"] + ": " + state["history"][0]["content"] print("test1") elif len(state["history"]) <= SUMMARIZE_LENGTH: context = "\n".join([h["role"] + ": " + h["content"] for h i...
Python
1
buffer.empty(): success, chunk = self.buffer_manager.get_from_buffer() if chunk: self._play_chunk(chunk) if self.immediate_stop.is_set(): logging.info("Immediate stop requested, aborting playback") break if self.on_playback_st...
Python
1
#!/usr/bin/env python3 """ Test script for OSC-based MCP server This script directly tests the OSC communication with REAPER """ import sys import time from pythonosc import udp_client # OSC settings (matching our server configuration) REAPER_OSC_HOST = "192.168.1.110" REAPER_OSC_PORT = 8000 def main(): print("T...
Python
1
import os from dotenv import load_dotenv load_dotenv("space-odyssey.env") def calculate_current_time_left() -> int: import time, datetime, pytz event_end_time_ist = ( int(os.getenv("EVENT_END_TIME")) if os.getenv("EVENT_END_TIME") else 1677054600 ) current_time_ist_float = time.mktime( ...
Python
1
# Database connection details DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'djangosites', 'USER': 'username', 'PASS': 'mypassword', } } # Django secret key, used to hash passwords etc. # Migrated from your initial settings.py SECRET_KEY ...
Python
1
import os import sys import urllib.parse SERVER_MODE = True AUTO_DISCOVER_SERVERS = False def build_postgresql_uri(): env_vars = { "PGADMIN_DB_URL_USERNAME": True, # required "PGADMIN_DB_URL_HOST": True, # required "PGADMIN_DB_URL_DATABASE": True, # required "PGADMIN_DB...
Python
1
_base_ = [ '../../configs/_base_/models/deeplabv3plus_r50-d8.py', '../../configs/_base_/datasets/pascal_voc12_aug.py', '../../configs/_base_/default_runtime.py', '../../configs/_base_/schedules/schedule_20k.py' ] optimizer = dict( type='SGD', lr=0.02, paramwise_cfg = dict( custom_keys={ ...
Python
1
&api).await; dbg! {&trackers}; trackers.expect("could not get torrent trackers"); } #[tokio::test] async fn contents() { let api = default_api().await.unwrap(); let torrents = queries::TorrentRequestBuilder::default() .filter(queries::TorrentFilter::Completed) .build() .unwrap()...
Rust
0
() { assert_eq!( structured_data("[abc][id aa=\"bb\"]").unwrap(), ( "", vec![ StructuredElement { id: "abc", params: vec![], }, StructuredElement { ...
Rust
0
Expr, _: &dyn Node) { let idents: Vec<Ident> = find_lhs_ids(&e.left); for ident in idents { self.check(ident.span, ident.to_id()); } } fn visit_update_expr(&mut self, e: &UpdateExpr, _: &dyn Node) { if let Expr::Ident(i) = &*e.arg { self.check(e.span, i.to_id()); } else { e.v...
Rust
0
line } } fn token(kind: TokenKind, line: u32) -> Token { Token { kind, line } } #[test] fn every_token() -> Result<()> { let source = fs::read_to_string("programs/tokens.chef")?; let subtokens = first_pass::process(&source); let expected_subtokens = { u...
Rust
0
ion_y(FRAC_PI_4) * translation(0.0, -2.0, 5.0)); let r = c.ray_for_pixel(100, 50); assert_eq!(r.origin(), point(0.0, 2.0, -5.0)); assert_eq!(r.direction(), vector(SQRT_2 / 2.0, 0.0, -SQRT_2 / 2.0)); } #[test] fn render_world_with_camera() { let w = World::default(); let mut c = Camera::new(11, 11,...
Rust
0
; if sorted[j].1 { continue; } // lighter / later with_siblings.1 = Some(*sorted[j].0); break; } } if i < length - 1 { let mut j = i; loop { if j == l...
Rust
0
aults() { let id = Id::random::<Provider>().expect(line_error!()); let key = Key::<Provider>::random().expect(line_error!()); let blobs = Blob::new(); let mut client = Client::new(id, blobs); client.add_vault(&key); let tx_id = client.create_record(key.clone(), b"data"...
Rust
0
fig.steganography.techniques = args.techniques logger.info(f"Using techniques: {args.techniques}") # Run the demo demo = QuickstartDemo(config, logger) results = demo.run_demo() # Display results logger.info("\n" + "=" * 50) logger.info("QUICKSTART DEMO RESU...
Python
1
tate) x_conv = self.conv_act_fn(x_conv) else: x_conv = x i, f, z, o = ( self.fgate(x_conv), self.igate(x_conv), self.zgate(x), self.ogate(x), ) y, slstm_state = self.slstm_cell( torch.cat([i, f, z, o], ...
Python
1
id(buf)?; if nid == NID::Crc { let crcs_defined = read_utils::read_all_or_bits(buf, num_folders as usize); for i in 0..num_folders { if crcs_defined.contains(i as usize) { folders[i as usize].has_crc = true; folders[i as usize].crc = read_utils::read_uint...
Rust
0
"""Utilities built on top of nlpaug. This file is meant to be lazy-imported because importing nlpaug can take time. See the discussion in https://github.com/autogluon/autogluon/issues/2706 """ import random from nlpaug import Augmenter from nlpaug.util import Method class InsertPunctuation(Augmenter): """ I...
Python
1
{{ is_marker( text, indx ) || is_in_regex( text, indx ) }// }}} // }}} /// Return true if character at indx is preceded by a single-quote//{{{ fn is_marker( text: &str, indx: usize ) -> bool {// {{{ // set curr_indx to just before char before char at current indx let mut curr_indx: usize = 0; if indx > ...
Rust
0
ordingTranscription { pub fn new() -> ApiV2010AccountRecordingRecordingTranscription { ApiV2010AccountRecordingRecordingTranscription { account_sid: None, api_version: None, date_created: None, date_updated: None, duration: None, price:...
Rust
0
e = false; break; } } else { beam_square = false; break; } } ...
Rust
0
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * # Simple Expands {{{# class _SimpleExpands(_VimTest): snippets = ('hallo', 'Hallo Welt!') class SimpleExpand_ExpectCorrectResult(_SimpleExpands): keys = 'hallo' + EX wanted = 'Hallo Welt!' class SimpleExpandTwice_Expe...
Python
1
{metro::Hash128_2, FastHash}; /// /// assert_eq!( /// Hash128_2::hash(b"hello"), /// 159488125173835797791070285137966695505 /// ); /// assert_eq!( /// Hash128_2::hash_with_seed(b"hello", 123), /// 337702340004473994826279129255403855211 /// ); /// assert_eq!( /// Hash128_2::hash(b"helloworld"), ///...
Rust
0
> HANDLES_MAX { &levels[0..HANDLES_MAX] } else { levels }; for (idx, level) in levels.iter().enumerate() { handle_data.values[idx] = *level as u8; } parse_retval!(unsafe { ioctl(self.fd, REQ_SET_LINE_VALUES, &mut handle_data) })?; O...
Rust
0
# # MIT License # # Copyright (c) 2020 Airbyte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, pu...
Python
1
put length against query length if (public_inputs.len() + 1) != pvk.query.len() { return Err(SynthesisError::MalformedVerifyingKey); } // e(A*G^{alpha}, B*H^{beta}) = e(G^{alpha}, H^{beta}) * e(G^{psi}, H^{gamma}) * // e(C, H) where psi = \sum_{i=0}^l input_i pvk.query[i] let mut g_psi = p...
Rust
0
import random import rospy from gazebo_msgs.srv import SpawnModel from geometry_msgs.msg import Pose, Point, Quaternion import rospkg def spawn_object(model=None, place=None, random_spawn=False): """ Spawn an object in Gazebo. Args: model (str, optional): Name of the model to spawn. pl...
Python
1
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: def helperPo...
Python
1
"Win32_Security"))] impl ::core::marker::Copy for FWPM_NET_EVENT_IKEEXT_QM_FAILURE0_1 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::clone::Clone for FWPM_NET_EVENT_IKEEXT_QM_FAILURE0_1 { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: ...
Rust
0
})?; Ok(Some(task)) } pub fn shutdown(&self) { info!("Scheduler stop."); } } #[cfg(test)] mod tests { use super::*; fn t_cron() { let expression = "0 30 9,12,15 1,15 May-Aug Mon,Wed,Fri 2018/2"; let schedule = Schedule::from_str(expres...
Rust
0
-> Option<&(dyn std::error::Error + 'static)> { match self { Error::ConnectionError(_migration, cause) => Some(&**cause), _ => None, } } } pub trait WrapMigrationError<T, E> { fn migration_err(self, msg: &str) -> Result<T, Error>; } impl<T, E> WrapMigrationError<T, E> ...
Rust
0
og::info!("CRITICAL time it took to collect: {:#?}", instant.elapsed()); instant = Instant::now(); stack.dump_all(heap).unwrap(); log::info!( "CRITICAL time it took to traverse: {:#?}", instant.elapsed() ); Ok(()) } #[test] fn mark_compact_random() { const STACK_SIZE: usize ...
Rust
0
checksum, encrypted = False).validate() def verify_shares_strings(secret: bytes, threshold: int, share_strings: List[str]) -> int: """ Verify that all combinations of 'threshold' number of shares can reconstruct the secret. Return the number of combinations tested. """ combs_tested = 0 ...
Python
1
_value(value: &syn::Lit) -> darling::Result<Self> { Ok(Self::Explicit(BlockContents::from_value(value)?)) } } impl ToTokens for DefaultExpression { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { match *self { Self::Explicit(ref block) => block.to_tokens(tokens), ...
Rust
0
def seg_default_ops(): """ default options to run pipeline """ chan1 = 1 chan2 = 0 diameter = 21.5 return { 'gpu': True , 'device': '0', # which gpu device to use, use an integer for torch, or mps for M1, (default: '0') 'model_type': './cellpose/model/cyto', 'pretrai...
Python
1
me `BaseSnackbar` to `MDSnackbar` class. For more information, see in the :class:`~kivymd.uix.behaviors.motion_behavior.MotionShackBehavior` and :class:`~kivymd.uix.card.card.MDCard` and class documentation. :Events: :attr:`on_open` Fired when a snackbar opened. :attr:`...
Python
1
"Custom server socket bind address (default: {})", DEF_BIND_ADDR )) .takes_value(true), ) .arg( clap::Arg::with_name("bind-port") .long("bind-port") .value_name("PORT") .he...
Rust
0
from collections import defaultdict from math import gcd from typing import List def max_coprime_components(values: List[int], edges: List[List[int]]) -> int: """ Finds the node whose removal leads to the maximum number of coprime components. """ n = len(values) tree = defaultdict(list) for u, ...
Python
1
unwrap().get_alive().unwrap(); let max_keys = 30; // Create some storage items for the contract. let vals: Vec<_> = (0..max_keys) .map(|i| (blake2_256(&i.encode()), (i as u32), (i as u32).encode())) .collect(); // Put value into the contracts child trie for val in &vals { Storage::<Test>::write(Sys...
Rust
0
_int = qual_char as u8 as f32 - 33.0; let p :f32 = TEN.powf((-1.0 * qual_int)/TEN); return p; }).collect(); let new_qual = combine_error_vectors(&qual_vec,&these_errors); *qual_vec = new_qual; } match &parser_getter.advance() { ...
Rust
0
''' Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees m...
Python
1
} } #[doc = r" Proxy"] pub struct _ALLOWBURSTW<'a> { w: &'a mut W, } impl<'a> _ALLOWBURSTW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) }...
Rust
0
os.path.exists(args.index_name): os.remove(args.index_name) if os.path.exists(faiss_document_store): os.remove(faiss_document_store) document_store = FAISSDocumentStore(embedding_dim=args.embedding_dim, faiss_index_factory_str="Flat") document_store.write_documents(dict...
Python
1
_json::to_string(self).unwrap() } pub fn from_string(data: &str) -> Blockchain { serde_json::from_str(data).unwrap() } pub fn get_field_names(&self) -> Vec<String> { return vec![ "genesis".to_string(), "child".to_string(), "parent".to_string(), ...
Rust
0
1, 31]` pub(crate) fn days_since_unix_epoch(year: i32, month: usize, month_day: i64) -> i64 { let is_leap_year = is_leap_year(year); let year = year as i64; let mut result = (year - 1970) * 365; if year >= 1970 { result += (year - 1968) / 4; result -= (year - 1900) / 100; resu...
Rust
0
# for now we need this for generation ) -> Union[Tuple, MambaCausalLMOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set `labels...
Python
1
klass(&k); { let fqname = "AddLdc.main2:([Ljava/lang/String;)I".to_string(); let meth = k.get_method_by_name_and_desc(&fqname).unwrap(); assert_eq!(ACC_PUBLIC | ACC_STATIC, meth.get_flags()); let mut vars = InterpLocalVars::of(5); let ret = exec_method(&mut repo, &meth, &m...
Rust
0
l Sha1Digest { pub(crate) const LENGTH: usize = 20; pub(crate) fn from_bytes(bytes: [u8; Self::LENGTH]) -> Self { Sha1Digest { bytes } } pub(crate) fn bytes(self) -> [u8; Self::LENGTH] { self.bytes } pub(crate) fn from_data(data: impl AsRef<[u8]>) -> Self { Sha1::from(data).digest().into() ...
Rust
0
(69, 1.0, 0.00454545454, 0.0), 0.5); assert_eq!(create_sawtooth_wave(69, 1.0, 0.00454545455, 0.0), -0.5); } #[test] fn test_square_wave() { assert_eq!(create_square_wave(0, 0.0, 0.0, 0.0), 0.0); assert_eq!(create_square_wave(69, 0.0, 0.0, 0.0), 0.0); assert_eq!(create_square_wave(69, 1.0, 0.0005682, 0....
Rust
0
} } }; } #[macro_export] macro_rules! arg_wrapper { ($name:ident, $wrapped_type:ty, $parser:expr) => { pub struct $name($wrapped_type); impl ::std::str::FromStr for $name { type Err = ::anyhow::Error; fn from_str(s: &str) -> ::std::result::Result<S...
Rust
0
""" Configuration file for backtesting and investment strategy evaluation. """ import os # Paths ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) RESULTS_DIR = os.path.join(ROOT_DIR, 'results') BACKTEST_DIR = os.path.join(RESULTS_DIR, 'backtest') # Ensure directories exist os.makedirs(BACKTE...
Python
1
from fastapi import FastAPI, Depends from app.routers import chat, generate, completions from app.services.load_balancer import LoadBalancer from app.services.metrics_collector import MetricsCollector from app.utils.config_loader import ConfigLoader from app.utils.dependencies import init_dependencies import asyncio #...
Python
1
#!/usr/bin/python3 """Create a new view for User objects""" from models import storage from models.user import User from api.v1.views import app_views from flask import jsonify, abort, request from flasgger.utils import swag_from @app_views.route('/users', methods=['GET'], strict_slashes=False) @swag...
Python
1
ck_config = { syscon.uartfrg.set_clkdiv(6); syscon.uartfrg.set_frgmult(22); syscon.uartfrg.set_frgdiv(0xff); UsartClock::new(&syscon.uartfrg, 0, 16) }; #[cfg(feature = "845")] // Set baud rate to 115200 baud let clock_config = UsartClock::new_with_baudrate(115200); #[...
Rust
0
1 = self.activation(self.fc_cf1s1(c3)) cf1s1 = self.dropout(cf1s1) if self.n_specific > 0: for farm1_specific_layer in self.farm1_specific_layers: cf1s1 = self.activation(farm1_specific_layer(cf1s1)) cf1s1 = self.dropout(cf1s1) out_layer_f0 = self.fc_o...
Python
1
(req)) => { let chid = req.info.chain_hex_id; let mtxins = self.lookup(&req.tx); if is_basic_valid_tx_request(&req, &mtxins, chid).is_err() { EnclaveResponse::UnknownRequest } else { ...
Rust
0
n_rx) = make_manager(2, 20); let remote_peers = make_sessions(&mut mgr, 1, 5000, SessionType::Outbound).await; let test_peer = remote_peers.first().expect("get first"); let session_closed = PeerManagerEvent::SessionClosed { pid: test_peer.owned_id(), sid: test_peer.session_id(), }; ...
Rust
0
source_file: source_file_info.source_file, tokens, comments, body: inner.body.iter().map(|value| get_view_for_stmt(value, bump)).collect(), }); let parent: Node<'a> = (&*node).into(); for value in node.body.iter() { set_parent_for_stmt(value, parent) } node } #[derive(Clone)] pub struct SeqE...
Rust
0
#!/usr/bin/env python # # Copyright 2019 Google LLC. All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list o...
Python
1
valorConcurso = float(input("Digite o valor do consurso em reais: ")) primeiroLugar = valorConcurso * 0.46 segundoLugar = valorConcurso * 0.32 terceiroLugar = valorConcurso * 0.22 print(primeiroLugar) print(segundoLugar) print(terceiroLugar)
Python
1
; pub use super::SMCAPTCTRLA0::EDGCNTA_EN; pub use super::SMCAPTCTRLA0::INP_SELA; pub use super::SMCAPTCTRLA0::ONESHOTA; } /// Capture Compare A Register pub mod SMCAPTCOMPA3 { pub use super::SMCAPTCOMPA0::EDGCMPA; pub use super::SMCAPTCOMPA0::EDGCNTA; } /// Capture Control B Register pub mod SMCA...
Rust
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
Python
1
.finish(); } } array_438.finish(); } } pub fn serialize_structure_slot_default_value( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::SlotDefaultValue, ) { if let Some(var_441) = &input.default_value { object.key("defaultValue").string(va...
Rust
0
# ----------------------------------------------------------------------------- # Title: Scientific Visualisation - Python & Matplotlib # Author: Nicolas P. Rougier # License: BSD # ----------------------------------------------------------------------------- # Illustrate the use of polar projection and rotated text...
Python
1
tion::ConnectionStart; use crate::codec::{Decode}; use bytes::{BytesMut, BufMut}; #[test] fn test_connection_start() { let mut connection_start = ConnectionStart::default(); connection_start.set_version_major(0); connection_start.set_version_minor(9); assert_eq!(connect...
Rust
0
import json import logging import os from functools import partial from typing import Union, Optional import torch from torch.hub import load_state_dict_from_url, download_url_to_file, urlparse, HASH_REGEX try: from torch.hub import get_dir except ImportError: from torch.hub import _get_torch_home as get_dir ...
Python
1
x1A0D766C,0x58F819E,0x48A1FCC,0xE296F62,0x83370E4,0xC9BA1D5,0x1E43290E,0xEE59A80,0x1FDD85F5,0x1F3819B6,0x1D9F]; pub const CURVE_PYA:[Chunk;NLEN]=[0x181A77F4,0x191AD22,0x1E9F842A,0x1E1E6CF6,0xD55B9D9,0x1D062533,0x15BB1323,0x7ECBC1,0x1A9EC2EF,0x1EE14CE0,0x1E96B271,0xA794439,0x1C544324,0xE6AD5DC,0x16429B0F,0x448E3]; pub c...
Rust
0
Error::EndExpected(position) } fn end_unexpected(position: Position) -> Self { Error::EndUnexpected(position) } fn unbound_variable(identifier: String, position: Position) -> Self { Error::UnboundVariable(identifier, position) } fn no_expression(position: Position) -> S...
Rust
0
t di; // directory index in PE header match magic { 0x10B => { imagebase = LittleEndian::read_u32(&pe_buf[52..56]) as u64; nr_dirs = LittleEndian::read_u32(&pe_buf[116..120]); di = 96 + 24; }, 0x20B => { imagebase = LittleEndian::read_u64(&...
Rust
0
n f'"{path}"' else: return path def version_string_to_url(version: pkg_version.Version) -> str: """ Make a Python package version string safe for URLs/folders. Our convention is to only replace all dots with dashes. """ return f"{version.major}-{version.minor}" def check_sphinx_vers...
Python
1
r.as_deref() } } impl MsgPackSerilization for ItemMetadata { type Output = ItemMetadata; fn to_msgpack(&self) -> Result<Vec<u8>> { Ok(rmp_serde::to_vec_named(self)?) } fn from_msgpack(data: &[u8]) -> Result<Self::Output> { Ok(rmp_serde::from_read_ref(data)?) } } #[derive(Seri...
Rust
0
(); border_cell_ports.insert(CellNo(0), vec![PortNo(0)]); let _dc = match Datacenter::construct( match Blueprint::new( self.graph_spec.num_cells, &self.graph_spec.edges, self.default_num_phys_ports_per_cell, ...
Rust
0
mp_eval_accuracy = accuracy(mc_logits, mc_labels) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0) nb_eval_steps += 1 eval_loss = eval_loss / nb_eval_steps eval_accuracy = eval_accuracy / nb_eva...
Python
1
'ResourceType': 'CloudFront Distribution', 'ResourceId': dist_id, 'ResourceName': domain_name, 'Origins': origin_domains, ...
Python
1
# coding: utf-8 import numpy as np def OR(x1, x2): x = np.array([x1, x2]) w = np.array([0.5, 0.5]) b = -0.2 tmp = np.sum(w * x) + b if tmp <= 0: return 0 else: return 1 if __name__ == '__main__': for xs in [(0, 0), (1, 0), (0, 1), (1, 1)]: y = OR(xs[0], xs[1]) ...
Python
1
t0 - t1) * G_SEC[(3 * i + 2) as usize]; x[16] = t3 + t2; x[24] = (t3 - t2) * G_SEC[(3 * i + 2) as usize]; i = i + 1; // x = x.offset(1); increment_by_mut(&mut x, 1); } } { let mut x: &mut [f32] = &mut...
Rust
0
simulation) as argument and will yield an interpolated //! value. //! //! If you try to sample in out-of-bounds sampling parameter, you’ll get no value. //! //! ``` //! # use splines::{Interpolation, Key, Spline}; //! # let start = Key::new(0., 0., Interpolation::Linear); //! # let end = Key::new(1., 10., Interpolatio...
Rust
0
t] fn test_part_one() { assert_eq!(part_one(">"), Ok(2)); assert_eq!(part_one("^>v<"), Ok(4)); assert_eq!(part_one("^v^v^v^v^v"), Ok(2)); } #[test] fn test_part_two() { assert_eq!(part_two("^v"), Ok(3)); assert_eq!(part_two("^>v<"), Ok(3)); assert_eq!(par...
Rust
0
} /// A unary operator. /// /// See IEEE 1076-2008 section 9.2. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum UnaryOp { /// The `not` operator. Not, /// The `abs` operator. Abs, /// The `+` sign operator. Pos, /// The `-` sign operator. Neg, /// A logical operator. Logic...
Rust
0
""" 数据库基础模型模块 """ import uuid from datetime import datetime from sqlalchemy import DateTime, func from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column class Base(DeclarativeBase): """SQLAlchemy 基类""...
Python
1
"msg": "an exam log message", "level": "INFO", "ts": "2022-03-27T13:11:48.58628Z", "format": "pretty", "foo": "bar" } { "msg": "test", "level": "INFO", "ts": "2022-03-27T13:11:48.586452Z", "format": "pretty", "fizz": "buzz" } { "msg": "test", "level": "ERRO", "ts": "2022-03-27T13:11:48.586477Z",...
Rust
0
) }; if context.is_null() { panic!("Couldn't create EGL rendering context."); } let surface = None; // Get visual id let mut visual_id = unsafe { mem::uninitialized() }; if unsafe { (self.gl.eglGetConfigAttrib)(display, config, EGL_NATIVE_VISUAL_ID, &mut visual_id) } == 0 { panic!("c...
Rust
0
# Copyright (c) 2014-2016 Hewlett Packard Enterprise Development LP # # Redistribution and use of this software in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # Redistributions of source code must retain the above copyright notice, # thi...
Python
1
columns_def="key UInt64, value UInt64", database="test", topic_list=topic_name, consumer_group=topic_name, keeper_path=keeper_path, replica_name=replica ) + ";" for replica in replica_names ] view_q...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 字符串的定义 s = "Hello, world!" # 也可以用str()函数将其他类型转换为字符串 s = str(123) # 输出"123" # 转义字符,比如\n表示换行,\t表示制表符,\r表示回车,\b表示退格,\f表示换页,\"表示双引号,\'表示单引号。"\\"表示反斜杠。 print("Hello, \"world\"!") # 字符串不想被转义时,可以用r''表示原始字符串,即所有的字符串都是直接输出,不进行转义。 print(r'Hello, "world"!\n') # 字符串可以用+运算符连接,也可...
Python
1
import sys import os import gzip from optparse import OptionParser import numpy as np import pandas as pd from inmoose.pycombat import pycombat_seq def main(argv): if len(argv) == 1: argv.append("--help") usage = "usage: %prog -i counts.tsv -b batch.tsv -o batch_corrected.tsv" desc = "Batch corre...
Python
1
erated_file.read_text() # Check variable substitution in title (from main file) assert "OverriddenAdvanced with Advanced Features" in content # Check main instructions with variable substitution assert "Project-specific: Follow OverriddenAdvanced guidelines" in content # Check...
Python
1
i] as usize + i); } step } #[test] fn q45_test() { assert_eq!( jump(vec![ 5, 6, 4, 4, 6, 9, 4, 4, 7, 4, 4, 8, 2, 6, 8, 1, 5, 9, 6, 5, 2, 7, 9, 7, 9, 6, 9, 4, 1, 6, 8, 8, 4, 4, 2, 0, 3, 8, 5 ]), 5 ); assert_eq!(jump(vec![2, 3, 0, 1, 4]), 2); assert_eq!(jump(vec![1, 1, 1, 1, 1]), 4);...
Rust
0
ding interrupt is disabled."] DISABLED = 0, #[doc = "1: Enabled. The SlvPending interrupt is enabled."] ENABLED = 1, } impl From<SLVPENDINGEN_A> for bool { #[inline(always)] fn from(variant: SLVPENDINGEN_A) -> Self { variant as u8 != 0 } } #[doc = "Field `SLVPENDINGEN` reader - Slave Pen...
Rust
0
from pdfrw import PdfReader, PdfWriter, PageMerge # Mapeo de campos del formulario PDF (usa nombres reales del PDF) campos = { 'topmostSubform[0].Page1[0].Line1_FullName[0]': 'JORGE ARTIGAS', 'topmostSubform[0].Page1[0].Line2_DOB[0]': '1985-07-12', 'topmostSubform[0].Page1[0].Line3_Country[0]': 'URUGUAY', ...
Python
1
inertias<Bodies>(&mut self, dt: Real, bodies: &Bodies) where Bodies: ComponentSet<RigidBodyMassProps> + ComponentSet<RigidBodyVelocity>, { if self.ndofs == 0 { return; // Nothing to do. } if self.augmented_mass.ncols() != self.ndofs { // TODO: do a resize...
Rust
0
import sys sys.path.append('/home/seb/tools/crypto/ngram_score') sys.path.append('/home/seb/tools/crypto/pycipher') from ngram_score import ngram_score fitness = ngram_score('/home/seb/tools/crypto/practicalcryptography.com/quadgrams.txt') import morse_talk #data = '-.-.-..-..--.--..-..---.-.--.--.' data = '-.-. - ...
Python
1
r_id] = True # TODO also parse daily limits # note: we must be logged in to see this page # otherwise we get "403 - forbidden" # (idiots just love to hide...) debrid_url = "https://neodebrid.com/hosts-status" debrid_id = get_netloc(debrid_url) debrid_html = get_debrid_html(debrid_url, debrid_id) debrid_hoster_map[de...
Python
1