text
string
label_name
string
labels
int64
potential_list = include_str!("putative_lost_ivotes.csv"); let mut summary = vec![]; let num_runs = 1000000; for electorate_line in potential_list.split('\n') { let (electorate,said_to_be_lost) = electorate_line.trim().split_once(',').unwrap(); if said_to_be_lost.is_empty() { continue; } ...
Rust
0
import azapy as az # define portfolio components symb = ['GLD', 'TLT', 'XLV', 'IHI', 'VGT'] # collect market data # set the end date of the time series # default start date is sdate='2012-01-01' edate = '2021-07-27' mktdata = az.readMkT(symb, edate=edate) # define the parameters of mLSD measure # coefficients - the ...
Python
1
from marshmallow import Schema, fields, validates, ValidationError, validate, validates_schema from budgetron.models import User, Role class BaseUserSchema(Schema): username = fields.String( required=True, validate=[ validate.Length(min=3, max=30), validate.Regexp( ...
Python
1
(&rpc_server)); app.at("/rpc/v0") .get(WebSocket::new(rpc_ws_handler::<DB, B>)) .post(rpc_http_handler::<DB, B>); info!("Ready for RPC connections"); app.listen(rpc_endpoint).await?; info!("Stopped accepting RPC connections"); Ok(()) } <reponame>JRegimbal/sieve-of-atkin extern c...
Rust
0
let target_y = self.position.1 + SEARCH_DIRECTIONS[self.direction][1] as i64; let target_position = (target_y * (width as i64) + target_x) as usize; let target_color = Color::new(image.pixel(target_position)); if target_color == argument.trace_color && (...
Rust
0
_entry(&mut map, "CloudWatchLogsLogGroupArn", &self.cloud_watch_logs_log_group_arn)?; ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for QueryLoggingConfig { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<QueryLoggingConfig, D::Error> { ...
Rust
0
= "Bit 22 - Memory 22 MBIST Status"] #[inline(always)] pub fn status22(&self) -> STATUS22_R { STATUS22_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - Memory 23 MBIST Status"] #[inline(always)] pub fn status23(&self) -> STATUS23_R { STATUS23_R::new(((self.bits >> 23)...
Rust
0
>, ) -> Result<fmm::build::TypedExpression, CompileError> { closures::compile_environment_pointer(fmm::build::bit_cast( fmm::types::Pointer::new(types::compile_sized_closure(definition, types)), compile_untyped_closure_pointer(), )) } fn compile_closure_pointer( function_type: &eir::types::...
Rust
0
import pytest import matplotlib.pyplot as plt from musicaiz import eval from musicaiz.eval import _DEFAULT_MEASURES @pytest.fixture def dataset_path(fixture_dir): return fixture_dir / "datasets" / "jsbchorales" / "train" @pytest.fixture def dataset2_path(fixture_dir): return fixture_dir / "datasets" / "jsb...
Python
1
antics(&self) -> Result<(), &str> { self.value.check_semantics()?; self.key.check_semantics()?; Ok(()) } } #[cfg(test)] mod test { use super::*; use crate::{javascript_lexer::Lexer, Parser}; macro_rules! test ( ($id: ident, $code:expr) => ( #[test] ...
Rust
0
itness::PedersenCommitment(wit_comm_ct_2)); let proof = ProofG1::new(&mut rng, proof_spec.clone(), witnesses.clone(), None).unwrap(); println!("Time taken to create proof {:?}", start.elapsed()); // Verifies the proof let start = Instant::now(); proof.verify(proof_spec, None).unwrap(); println...
Rust
0
[0u8; 3]; b64decode(valid.as_bytes(), &mut decoded[..]).ok().unwrap(); } { let valid = "0AA="; let mut decoded = [0u8; 3]; b64decode(valid.as_bytes(), &mut decoded[..]).ok().unwrap(); } { let valid = "0A00"; let mut decoded = [0u8; 3]; b64decode...
Rust
0
for i in 0..N { sign.t[i] = gauss_sample!(); u[i] = gauss_sample!(); } xmu(&mut v, &sign.t, &W); fft(&mut v); xmu(&mut vv, &v, &self.a); fft(&mut vv); xmu(&mut v, &vv, &R); flp(&mut v); for ...
Rust
0
mut ratios = Vec::new(); for i in 0_i16..1000 { ratios.push(r32::from(i)); } c.bench_function("r32_mult 1000", |b| b.iter(|| { ratios.iter().fold(black_box(r32!(1)), |a, &b| a * b) })); } pub fn main() { env_logger::init(); trillium_tokio::run(|conn: trillium::Conn| async move { conn.ok("ok!") }); } <g...
Rust
0
from .chat import chat from .knowledge_base_chat import knowledge_base_chat from .openai_chat import openai_chat from .search_engine_chat import search_engine_chat
Python
1
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let root_dir = manifest_dir .parent() .context("Failed to get the project root directory.")?; Ok(root_dir.to_path_buf()) } <filename>day-12/src/main.rs<gh_stars>1-10 use std::collections::HashMap; use std::fs; #[derive(Debug)] s...
Rust
0
ht; let ref weights_jl = site_data[site_j].bond_weight; // NOTE: // * In the REBO paper, these weights are the same as all the others. // * In the AIREBO paper, these weights use a slightly different (shorter) interval: let _the_interval_airebo_would_use = |i...
Rust
0
pub fn constant<T>(mut self, name: &'a str, value: T) -> Self where T: Into<Zval>, { let mut value = value.into(); if value.is_string() { let val = value.string().unwrap(); unsafe { ext_php_rs_zend_string_release(value.value.str) }; value.set_persiste...
Rust
0
pe)), } } #[inline] fn timestamp( array: &mut MutablePrimitiveArray<i64>, time_unit: TimeUnit, logical_type: Option<PrimitiveLogicalType>, ) { let unit = if let Some(PrimitiveLogicalType::Timestamp { unit, .. }) = logical_type { unit } else { return; }; match (unit, tim...
Rust
0
style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. use std::os::raw; use std::ptr; use bitflags::bitflags; use crate::raw::structure_types::{ VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, VK_STR...
Rust
0
ew, (4, 4)).T modelview_inv = np.linalg.inv(modelview) pcloud.transform(modelview_inv) ret[pcd_stem] = np.asarray(pcloud.points) return ret def write_correspondence_ply(file_path, pcloudi, pcloudj, ...
Python
1
import cv2 def candy_count(image,desiredArea=100): # greyscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Blured blured = cv2.GaussianBlur(gray, (3, 3), None) # adaptive threshholding threshAdap = cv2.adaptiveThreshold(blured, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11...
Python
1
.root_hash, file_hash: prev1.file_hash, }); out_prev.push(BlockIdExt { shard_id: shard2, seq_no: prev2.seq_no, root_hash: prev2.root_hash, file_hash: prev2.file_hash, }); prev_seqno = max(prev...
Rust
0
# coding=utf-8 # Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/L...
Python
1
raise ValueError("Invalid element '%s'" % e) self._kvstore.add_many(d) def get_data(self, uuid): """ Get the data element the given uuid references, or raise an exception if the uuid does not reference any element in this set. :raises KeyError: If the given uuid...
Python
1
.scatter(mu_X[0], mu_X[1], color='black', s=64, label='Mean $(\mu_R, \mu_S)$') ax.scatter(form.design_point_x[0][0], form.design_point_x[0][1], color='tab:orange', marker='*', s=100, label='Design Point', zorder=2) ax.set(xlabel='Resistence $R$', ylabel='Stress $S$', xlim=(145, 255), ylim=(115, 18...
Python
1
The message is stored in the // Terra contract state and can be read out via QueryMsg. ExecuteMsg::RecvMessage { vaa } => { // Parse VAA and decode Payload into message. let vaa = parse_vaa(deps, env, &vaa)?; let msg = Message::try_from_slice(&vaa.payload) ...
Rust
0
def menor3(m1,m2,m3): """Metodo que encuntra el menor de tres numeros Args: m1 (int): valor monetario de la moneda 1 m2 (int): valor monetario de la moneda 2 m3 (int): valor monetario de la moneda 3 Returns: int: el menor de los 3 valores """ x = 0; z = 0; ...
Python
1
# SPDX-FileCopyrightText: AISEC Pentesting Team # # SPDX-License-Identifier: Apache-2.0 import sys assert sys.platform.startswith("linux"), "unsupported platform" import pytest from pydantic import ValidationError from gallia.transports import TargetURI from gallia.transports.doip import DoIPConfig from gallia.tran...
Python
1
Err(Error::MediaPlayerError( "AudioLibError(\"stop\")".to_string() )), result ); } #[test] fn test_timeout_run() { let mut rfid_media_player = open( OkMediaPlayer, TimeoutRfidReader, SomeTrackStore(trac...
Rust
0
"""Constants for the siren component.""" from enum import IntFlag from functools import partial from typing import Final from homeassistant.helpers.deprecation import ( DeprecatedConstantEnum, check_if_deprecated_constant, dir_with_deprecated_constants, ) DOMAIN: Final = "siren" ATTR_TONE: Final = "tone...
Python
1
>) -> EmitterWriter { let stderr = io::stderr(); let use_color = match color_config { Always => true, Never => false, Auto => stderr.get_ref().isatty() }; if use_color { let dst = match term::stderr() { Some(t) => Termi...
Rust
0
self.assertFalse(torch.isnan(log_prob).any()) self.assertFalse(torch.isinf(log_prob).any()) def test_sample(self): num_samples = 10 context_size = 20 input_shape = [2, 3, 4] context_shape = [2, 3, 8] dist = normal.ConditionalDiagonalNormal(input_shape) ...
Python
1
unner = System::new(); runner.block_on(async move { let _res = HttpServer::new(|| { App::new() .wrap(middleware::HeadersMiddlewareFactory) .route("/info", web::get().to(get_own_info)) .route("/local_fee", web::get().to(get_l...
Rust
0
Pubkey, accounts: &[AccountInfo]) -> ProgramResult { let accounts = Accounts::parse(program_id, accounts)?; let mut market_state = DexState::get(accounts.market)?; check_accounts(&market_state, &accounts).unwrap(); let base_vault_data = Account::unpack_from_slice(&accounts.base_vault.data.borrow_mut(...
Rust
0
"Volatile invoked", "Memoized2 invoked"]); query.memoized2(); query.assert_log(&[]); } <filename>tests/extended_tests.rs // File autogenerated with /scripts/generate_tests.py extern crate uritemplate; use uritemplate::UriTemplate; // Additional Examples 1 #[test] fn test_additional_examples_1() { let mu...
Rust
0
import numpy as np import pandas as pd from pandas import DataFrame, Series from typing import Any, List, Tuple, Union, Callable, Optional import statsmodels.api as sm from ..utils.operator import StatsLogit, NumRange from ..utils.logger import LoggerMixin from .psi import psi from .utils import lift from .binary_metr...
Python
1
] fn some_simple_lcm() { assert_eq!(18, lcm(6, 9)); assert_eq!(20, lcm(5, 4)); } #[test] fn test_modulo_mul() -> Result<(), MathError> { let a = 1_234_567_890_123_456i64; let b = 98_765; let result = modulus_mul(a, b, 3_333_333_333_333_333)?; assert_eq!(...
Rust
0
"eventLastSeen": "2019-11-13T00:25:31.619Z", "evidence": { "threatIntelligenceDetails": [ { "threatListName": "GeneratedFindingThreatListName", "threatNames": ["GeneratedFindingThre...
Python
1
g, span_error_msg(span, source_map) ), InternalError::Parse { error } => format!( "typescript parsing error: {}\n source: {}", error.kind().msg(), span_error_msg(error.span(), source_map) ), ...
Rust
0
{} // USART1 RX unsafe impl RxPin<USART1> for PB15<Input<Floating>, AF4> {} unsafe impl RxPin<USART1> for PA10<Input<Floating>, AF7> {} unsafe impl RxPin<USART1> for PB7<Input<Floating>, AF7> {} // USART2 RX unsafe impl RxPin<USART2> for PA3<Input<Floating>, AF7> {} unsafe impl RxPin<USART2> for PD6<Input<Floating>,...
Rust
0
> """ # Render the CSS style st.markdown(text_area_style, unsafe_allow_html=True) # Display the text area with the specified text for i, text in enumerate(st.session_state.conversation_memory): # User messages on the right if text.startswith("You: "): with st.container(...
Python
1
"""Beam-search ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from common.ops import gather_ops def rnn_beam_search(update_fn, initial_state, sequence_length, beam_width, begin_token_id, end_token_id, ...
Python
1
** 2) + ((y - center_y) ** 2) / (radius_y ** 2) <= 1 elif area_type == 'polygon': return cv2.pointPolygonTest(np.array(area_points, dtype=np.float32).reshape((-1, 1, 2)), (x, y), False) >= 0 def point_in_exclude_area(area_types, area_points, x, y): return point_in_area(area_types[0], area_points[0], x...
Python
1
start().await.unwrap(); } <filename>src/cargo/core/shell.rs use std::fmt; use std::io::prelude::*; use std::io; use term::Attr; use term::color::{Color, BLACK, RED, GREEN, YELLOW}; use term::{Terminal, TerminfoTerminal, color}; use self::AdequateTerminal::{NoColor, Colored}; use self::Verbosity::{Verbose, Normal, Qui...
Rust
0
.write(partition_storage_offset, &data) .or(Err(FatError::WriteFailed))?; } FatFsType::Fat12 => { // Welcome to the IBM world let mut data = [0x0u8; 2]; fs.storage_device .lock() .read(pa...
Rust
0
0, 'loc_55B0'), (-1, 'loc_560B'), ) def _loc_55B0(): pass label('loc_55B0') ChrTalk( 0x000B, ( '#0040240128V#037F呵,原来如此……', TxtCtl.Enter, TxtCtl.Clear, '#0040240129V看来是需要\n', '我这个天才的力量啊。', TxtCtl.Enter, ...
Python
1
from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import PydanticOutputParser from pydantic import BaseModel, Field import os class DescribeOutput(BaseModel): """Model for structured output of description.""" thought: str = Field(description="Private reasoning about the strat...
Python
1
::Register8(register) => self.registers.write_byte(register, value), Operand::Direct8(_) => unimplemented!(), Operand::Direct16(address) => self .memory .borrow_mut() .write_byte(*address as usize, value), Operand::RegisterIndirect(regi...
Rust
0
file let content = fs::read_to_string(path).map_err(|_| ())?; // parse & add data let data = parse_jsonc(&content).ok_or(())?; self.add_data(data); Ok(()) } /// Returns the buff definition with the given id. pub fn get_buff(&self, buff_id: u32) -> Option<&DefKind> ...
Rust
0
type Target = spidev::Spidev; fn deref(&self) -> &Self::Target { &self.0 } } impl ops::DerefMut for Spidev { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } pub mod clip; pub mod time; pub mod maintenance; pub use clip::Clip;<filename>src/error.rs // MIT License // // C...
Rust
0
>0 #[cfg(feature = "sync")] pub mod sync; #[cfg(feature = "async")] pub mod r#async; use std::{error::Error, io::Stdout}; use tui::{ backend::CrosstermBackend, layout::{Alignment, Rect}, style::{Color, Style}, widgets::{Block, BorderType, Borders, Paragraph, Text}, Frame, }; #[derive(Debug, Defaul...
Rust
0
H_DATA}/CANDLES/{MARKET}/') if not os.path.exists(directory): os.makedirs(directory) file_name = f'{directory}/CANDLES_{res}.json' last_line =read_last_line(file_name) candles.reverse() for candle in candles: candle.pop("orderbookMidPriceOpen", None) candle.pop("orderbookM...
Python
1
GUID, pub usnLastObjChangeSynced: i64, pub usnAttributeFilter: i64, pub ftimeLastSyncSuccess: super::super::Foundation::FILETIME, pub ftimeLastSyncAttempt: super::super::Foundation::FILETIME, pub dwLastSyncResult: u32, pub cNumConsecutiveSyncFailures: u32, } #[cfg(feature = "Win32_Foundation")] ...
Rust
0
optional output which can be one of "xml" (default), "html", "text" or "c14n", *default_namespace* sets the default XML namespace (for "xmlns"). Returns an (optionally) encoded string containing the XML data. r}rrrrurStringIOBytesIOrrgetvalue)r6rrrrrustreams ...
Python
1
ll; use crate::lc::common::TreeNode::TreeNode; /// Rc, RefCell, Vec impl Solution { pub fn kth_smallest(root: Option<Rc<RefCell<TreeNode>>>, k: i32) -> i32 { let mut stack = vec![]; let mut p = root; let mut count = 0; while p.is_some() || !stack.is_empty() { if let Som...
Rust
0
d = StaticVec::<i32, 12>::new(); d.insert_from_slice(0, b.as_slice()); d.insert(0, c.remove(0)); d.append(&mut c); forget(a1); forget(a2); forget(b); forget(c); d }; fn main() { println!("{:?}", S1); println!("{:?}", S2); println!("{:?}", B); println!("{:?}", S3); println!("{:?}", SLICE); ...
Rust
0
ken: Token![=], path: Path, } impl Parse for CratePath { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { Ok(CratePath { _crate_token: input.parse()?, _eq_token: input.parse()?, path: input.parse()?, }) } } impl From<CratePath> for Path { fn from(CratePath { path, ..}: C...
Rust
0
ze, Deserialize, Debug, PartialEq, Eq, Clone)] #[repr(C)] pub struct LoginPacket { pub login: String, pub password: String, } impl LoginPacket { pub fn new(login: String, password: String) -> LoginPacket { LoginPacket { login: login, password: password, } } } ...
Rust
0
ion = np.random.randint(0, self.n_actions) print(action) return action def learn(self): if self.learn_step_counter % self.replace_target_iter == 0: self.sess.run(self.target_replace_op) print('\ntarget_params_replaced\n') # -------------------------从记忆库中提取记忆...
Python
1
array([1], dtype=np.int64), 'cpu', 0) history_len = onnxruntime.OrtValue.ortvalue_from_numpy(np.array([0], dtype=np.int64), 'cpu', 0) attention_mask_0 = onnxruntime.OrtValue.ortvalue_from_numpy(np.array([0], dtype=np.int8), 'cpu', 0) attention_mask_1 = onnxruntime.OrtValue.ortvalue_from_numpy(np.array([1], ...
Python
1
re = "dox", doc(cfg(feature = "v2_62")))] //fn connect_async<P: FnOnce(Result<gio::IOStream, glib::Error>) + Send + 'static, Q: FnOnce(Result<gio::IOStream, glib::Error>) + Send + 'static>(&self, uri: &mut URI, cancellable: Option<&impl IsA<gio::Cancellable>>, progress_callback: P, callback: Q) { // unsafe {...
Rust
0
BKP_DR34 ((uint16_t)0x009C) #define BKP_DR35 ((uint16_t)0x00A0) #define BKP_DR36 ((uint16_t)0x00A4) #define BKP_DR37 ((uint16_t)0x00A8) #define BKP_DR38 ((uint16_t)0x00AC) #define BKP_DR39 ...
Rust
0
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/gui/impl/lobby/veh_post_progression/tooltips/role_slot_tooltip_view.py import typing from gui.Scaleform.daapi.view.lobby.veh_post_progression.veh_post_progression_vehicle import g_postProgressionVehicle from gui.impl.gen import R fr...
Python
1
print('block 3 output: {}'.format(x.shape)) x = self.block4(x) if self.verbose: print('block 4 output: {}'.format(x.shape)) x = self.block5(x) if self.verbose: print('block 5 output: {}'.format(x.shape)) x = x.view(x.shape[0], -1) x = self...
Python
1
2192); } if let Some(var_2193) = &input.status { object.key("Status").string(var_2193); } } pub fn serialize_structure_crate_model_aws_rds_db_cluster_member( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::AwsRdsDbClusterMember, ) { if input.is_cluster_write...
Rust
0
ut host| { host.restart_policy = host.restart_policy.or_else(|| { Some(RestartPolicy { name: Some(RestartPolicyNameEnum::UNLESS_STOPPED), ..Default::default() }) ...
Rust
0
[u32] = &[0, 2, 3, 3, 1, 0]; const UV_VARIANT_1: &[Vector2<f32>] = &[ Vector2 { x: 0.0, y: 0.0 }, Vector2 { x: 1.0, y: 0.0 }, Vector2 { x: 0.0, y: 1.0 }, Vector2 { x: 1.0, y: 1.0 }, ]; const UV_VARIANT_2: &[Vector2<f32>] = &[ Vector2 { x: 1.0, y: 0.0 }, Vector2 { x: 1.0, y: 1.0 }, Vector2...
Rust
0
x=input_parallel, quant_weight=self.quant_weight, quant_dtype=self.quant_dtype, quantization_config=self.quantization_config, weight_quantize_algo=self.weight_quantize_algo, dtype=self._dtype, quant_scale=self.quant_...
Python
1
else: result.save(output_path, "PNG") self.log(f"[SUCCESS] Saved RGB image: {os.path.basename(output_path)}") # Verify output file was created if not os.path.exists(output_path): self.log("[ERROR] Output file genera...
Python
1
width=600, height=900, showlegend=False,xaxis=axis, yaxis=axis,template="none") fig.write_image(savePath) def get_color_hex(value, light_color, dark_color): """Function returns hexadecimal color based on value between 0 and 1.""" # Check value is bounded first value = max(0, min(1, value)) # I...
Python
1
s(row=row, column=start_col + 9)[0] text_language_menu = frame.grid_slaves(row=row, column=start_col + 10)[0] # 更新参考语言下拉菜单的选项 ref_language_menu['menu'].delete(0, 'end') for choice in ref_language_choices: ref_language_menu['menu'].add_command(label=choice...
Python
1
''' Test creating for java.io.Closeable dunder ''' from __future__ import absolute_import import unittest from jnius import autoclass, JavaException, protocol_map class TestCloseable(unittest.TestCase): ''' TestCase for using java.io.Closeable dunder ''' def test_stringreader_closeable(self): ...
Python
1
Debug, PartialEq, Eq, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Env { pub current_coinbase: H160, #[serde(deserialize_with = "deserialize_str_as_u256")] pub current_difficulty: U256, #[serde(deserialize_with = "deserialize_str_as_u256")] pub current_gas_limit: U256, #[serde(des...
Rust
0
ask_price, quantity) time.sleep(2) # 循环检测间隔 # 检查订单状态,处理成交或取消的订单 # self.check_order_status() time.sleep(5) # 循环检测间隔 except (ConnectionError, ProtocolError) as e: logger.error(f"网络连接异常: {e}") logger.info(f"将在{r...
Python
1
,0); generate_single!(A,B,C,D,E,F,G,H,I,J,K,L,M,N; N,M,L,K,J,I,H,G,F,E,D,C,B,A; 13,12,11,10,9,8,7,6,5,4,3,2,1,0); generate_single!(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O; O,N,M,L,K,J,I,H,G,F,E,D,C,B,A; 14,13,12,11,10,9,8,7,6,5,4,3,2,1,0); generate_single!(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P; P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A; 15,14,1...
Rust
0
+ BS_OFFSET_RET1 ret2_rip = bs_rip + BS_OFFSET_RET2 cmp_rip = bs_rip + BS_OFFSET_CMP je_rip = bs_rip + BS_OFFSET_JE # sgx-step somehow consistently skips this je bs_idx_entry = rips.index(bs_rip) try: bs_idx_ret = rips.index(ret1_rip) except ValueError: bs_idx_ret = rips.index(ret2_rip) pr...
Python
1
::Constant(F::from_u128(2u128.pow(WORD_BITS))) * flag_n) + d], ) }); conf } pub fn assign_sum<F: FieldExt>( &self, region: &mut Region<'_, F>, d: F, offset: usize, ) { region .assign...
Rust
0
(raw) } } impl fff::PrimeField for Fp { type Repr = FpRepr; const NUM_BITS: u32 = 381; const CAPACITY: u32 = Self::NUM_BITS - 1; const S: u32 = 1; fn from_repr(repr: Self::Repr) -> Result<Self, fff::PrimeFieldDecodingError> { if FpRepr(repr.0) < MODULUS { let mut out = bls...
Rust
0
import hashlib import time from typing import Dict def perform_pouw_task(index: int, sector: str, data: Dict, shard_id: int, token: str) -> Dict: start_time = time.time() if token == "GRN": if sector == "cannabis": batch_id = data.get("batch_id", "batch-001") thc_level = data.ge...
Python
1
self = fork; } ok } fn expect_tt(&mut self) -> Result<tt::TokenTree, ()> { match self.peek_n(0) { Some(tt::TokenTree::Leaf(tt::Leaf::Punct(punct))) if punct.char == '\'' => { return self.expect_lifetime(); } _ => (), } ...
Rust
0
import sys import time lista = [0, 1, 2, 3, 4, 5] lista = iter(lista) print(next(lista)) print(next(lista)) print(next(lista)) print(hasattr(lista, '__next__')) ## geradores l1 = [x for x in range(1000)] #iteravel l2 = (x for x in range(1000)) #gerador for v in l2: print(v) def gera(): for n in range(100...
Python
1
__author__ = "Sritej K V R <skanakad@cisco.com>" from unicon.bases.routers.connection import BaseSingleRpConnection from unicon.bases.routers.connection import BaseDualRpConnection from unicon.plugins.iosxr import service_implementation as svc from unicon.plugins.iosxe.service_implementation import Ping as IosXePing...
Python
1
from pydantic import BaseModel class TruckBase(BaseModel): name: str speed: float weight: float max_cargo_weight: float height: float class Truck(TruckBase): id: str
Python
1
import math N1=float(input("Enter the number:")) P1=float(input("Enter the power you want:")) A1=pow(N1,P1) print(A1)
Python
1
/// This means that this input type will completely avoid nom's streaming features /// and `Incomplete` results. #[derive(Clone, Copy, Debug, PartialEq, Hash)] pub struct CompleteByteSlice<'a>(pub &'a [u8]); impl<'a> AtEof for CompleteByteSlice<'a> { fn at_eof(&self) -> bool { true } } impl<'a> Slice<Range<us...
Rust
0
embed_dim=embed_dim, num_heads=num_heads, ff_dim=ff_dim, name=f'transformer_level_{i}_layer_{j}' )(x) enhanced_features.append(x) return enhanced_features if __name__ == '__main__': print("Model loaded") print("Tenso...
Python
1
# -*- coding: utf-8 -*- # Copyright (C) 2017 Johannes F. Knauf # # This program 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. # # Thi...
Python
1
There are a number of ways that the trans backend could choose to //! compile this (e.g. a `[bool, ..10]` array for each such moved array; //! or an `Option<uint>` for each moved array). From the viewpoint of the //! borrow-checker, the important thing is to record what kind of fragment //! is implied by the relevant...
Rust
0
import os import json import pandas as pd import numpy as np from sentence_transformers import SentenceTransformer import faiss import pickle def split_into_chunks(text, max_words=100, overlap=20): words = text.split() chunks = [] for i in range(0, len(words), max_words - overlap): chunk = " ".joi...
Python
1
// Returns the divisor, the number of digits processed, and the // number of leading zeros in the divisor. // // These values were calculated using the following script: // // ```text // import math // // u64_max = 2**64 - 1 // u128_max = 2**128-1 // // def is_valid(x): // return ( // x <= u64_max /...
Rust
0
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html import os import sys sys.path.insert(0, os.path.abspath("../..")) # -- Project information ------------------------...
Python
1
import tempfile import unittest from transformers import LlavaConfig class LlavaConfigTest(unittest.TestCase): def test_llava_reload(self): """ Simple test for reloading default llava configs """ with tempfile.TemporaryDirectory() as tmp_dir: config = LlavaConfig() ...
Python
1
glib_wrapper! { pub struct RTSPServer(Object<ffi::GstRTSPServer, ffi::GstRTSPServerClass>); match fn { get_type => || ffi::gst_rtsp_server_get_type(), } } impl RTSPServer { pub fn new() -> RTSPServer { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi...
Rust
0
free_cluster = LittleEndian::read_u32(&block[0x1e8..0x1ec]); if fs_free_cluster <= fs.boot_record.cluster_count { free_cluster = fs_free_cluster; } } Ok(FatFileSystemInfo { last_cluster: AtomicU32::new(last_cluster), free_cluster: AtomicU3...
Rust
0
elf.wait_for_element((By.XPATH, "//input[@placeholder='Enter password']")) # password_input.send_keys(self.TEST_PASSWORD) # submit_button = self.wait_for_clickable((By.XPATH, "//button[@type='submit']")) # submit_button.click() # self.scroll_and_accept_terms() # logout_button = s...
Python
1
all_metrics_times[app_id] = [] all_metrics_times[app_id].append(metric_timing) def print_all_metrics(metrics): print('Metrics Summary') for app_id in sorted(metrics): first = True for single_query_metrics in metrics[app_id]: print_app_metrics(app_id, single_query_metrics, first) first = F...
Python
1
N=5 for i in range(N):# range(desde, hasta, paso) x=int(input()) if(x>=90 and x<=100): nota=5 elif(x>=80 and x<90): nota=4 elif(x>=70 and x<80): nota=3 elif(x>=60 and x<70): nota=2 else: nota=1 print("La nota es:",nota)
Python
1
# condition ?? # print("Enter your numbers ") # a = int(input("Enter number :")) # if a < 0 : # print("Negative number") # elif a == 0 : # print("Zero") # elif 0 < a <= 10 : # print("Between 1 and 10") # elif 100>a>10: # print("Between 11 and 100") # else : # print("Greater than 100") # # # conditio...
Python
1
orter = DOIURLImporter( db_config=self.db_config, csv_file=str(self.csv_file), batch_size=2, # Small batch size for testing create_tables=False, resume=False ) # Set start row to skip first row importer.start_row = 1 ...
Python
1