text
string
label_name
string
labels
int64
e=0.0, image_size=224, out_features=None, out_indices=None, **kwargs, ): super().__init__(**kwargs) self.num_channels = num_channels self.patch_size = patch_size self.num_stages = num_stages self.hidden_sizes = [96, 192, 384, 768] if hidden_si...
Python
1
} } } <reponame>abarrerah/Frontier<gh_stars>0 // // This file was auto-generated, do not edit directly // /* Copyright © 2008-2013 <NAME> Copyright © 2013 <NAME> Copyright © 2013 <NAME> Copyright © 2010-2013 Intel Corporation Permission is hereby granted, free of charge, to any ...
Rust
0
>) -> Bewit<'a> { Bewit { id: Cow::Borrowed(id), exp, mac: Cow::Owned(mac), ext: match ext { Some(s) => Some(Cow::Borrowed(s)), None => None, }, } } /// Generate the fully-encoded string for this Bewit ...
Rust
0
er { pub fn new(study: &StudyRecipe) -> Result<Self> { let opt = RunnerOpt { parallelism: unsafe { NonZeroUsize::new_unchecked(1) }, quiet: true, }; let mpb = MultiProgress::with_draw_target(ProgressDrawTarget::hidden()); let mut this = track!(Self::with_mpb(s...
Rust
0
ct or issuer, 'exp': expires_at or (now + expires_in), 'iat': issued_at or now, 'jti': assertion_id or str(uuid.uuid4()), } if not_before: payload['nbf'] = not_before payload.update(additional_claims or {}) try: str_or_bytes...
Python
1
rch, and ordering""" # Filter by price range + search + ordering url = f"{self.list_url}?min_price=10&max_price=100&search=game&ordering=discount_price" response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['...
Python
1
to_string()); } #[test] fn test_part_a() { let s: String = "dabAcCaCBAcCcaDA".to_string(); assert_eq!(part_a(&s), 10); let s: String = "dbcCCBcCcD".to_string(); assert_eq!(part_a(&s), 6); let s: String = "daAcCaCAcCcaDA".to_string(); assert_eq!(part_a(&s), 8)...
Rust
0
); let (arg_y, arg_d) = if active_advent { (arg_y.default_value(&y), arg_d.default_value(&d)) } else { (arg_y.required(true), arg_d.required(true)) }; // Session key let arg_s = Arg::with_name("session").short("s").takes_value(true); let session_key; let arg_s = match get_s...
Rust
0
size = 1 << size_log; group.bench_with_input(BenchmarkId::from_parameter(size), &size, |b, _| { let coeffs = PolynomialCoeffs::new(F::rand_vec(size)); b.iter(|| coeffs.clone().fft_with_options(None, None)); }); } } pub(crate) fn bench_ldes<F: Field>(c: &mut Criterion) { ...
Rust
0
# The counter in the database is bigger continue sys.stdout.write("\r {0!s}: {1!s} ".format(processed, count[0])) r = ( linotp_session.query(LinToken) .filter_by(LinOtpTokenSerialnumber=count[0]) .update({"LinOtpCount": count[1]}) ) ...
Python
1
from typing import Optional from fastapi import Depends, Request from fastapi_users import BaseUserManager, FastAPIUsers, IntegerIDMixin from fastapi_users.authentication import ( AuthenticationBackend, BearerTransport, JWTStrategy, ) from fastapi_users.db import SQLAlchemyUserDatabase from sqlalchemy.ext....
Python
1
31665577, -12180464, -16186830, 1491339, -18368625, 3294682, 27343084, 2786261, -30633590, -14097016, ]), }, GePrecomp { y_plus_x: Fe([ -14467279, -683715, -33374107, 7448552, 19294360, 14334329, -19690631, 2355319, -19284...
Rust
0
_in.read(1) if c == "R": break r += c return list(int(part) for part in r.split(";")) def set_pos(pos): print(f"\x1b[{pos[0]};{pos[1]}H", flush=True, file=tty_out, end="") print("\r\n", flush=True, file=tty_out) error...
Python
1
:param _InstanceState: 实例状态 注意:此字段可能返回 null,表示取不到有效值。 :type InstanceState: str """ self._TaskId = None self._CurRunDate = None self._LifeRound = None self._RunType = None self._Tries = None self._InstanceLifeDetailDtoList = None self._RunnerState...
Python
1
def calculate_price(price, seasonal=False, promo_code=None, loyalty=None, quantity=1): if price < 0: raise ValueError("Price cannot be negative") # Seasonal discount if seasonal: price -= price * 0.10 # Promo code logic if promo_code == "SAVE5" and price >= 50: price ...
Python
1
) -> CLK160_OEN_W { CLK160_OEN_W { w: self } } #[doc = "Bit 6 - reg_clk_320m_oen"] #[inline(always)] pub fn clk_320m_oen(&mut self) -> CLK_320M_OEN_W { CLK_320M_OEN_W { w: self } } #[doc = "Bit 7 - reg_clk_adc_inf_oen"] #[inline(always)] pub fn clk_adc_inf_oen(&mut self) ...
Rust
0
[AtomicU64::new(0), AtomicU64::new(0)], [AtomicU64::new(0), AtomicU64::new(0)], [AtomicU64::new(0), AtomicU64::new(0)], [AtomicU64::new(0), AtomicU64::new(0)], ], } } pub fn SetValue(&self, cpuId: usize, idx: usize, val: u64) { self.values[cpuId][idx].store(val, Ordering::Re...
Rust
0
# Imports import discord from discord.ext import commands # Intents intents = discord.Intents.default() intents.message_content = True # Prefix bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) # Custom Status @bot.event async def on_ready(): print("The bot is now online") await bot.cha...
Python
1
# *************************************************************** # Copyright (c) 2023 Jittor. All Rights Reserved. # Maintainers: # Guoye Yang <498731903@qq.com> # Dun Liang <randonlang@gmail.com>. # # This file is subject to the terms and conditions defined in # file 'LICENSE.txt', which is part of this s...
Python
1
mklink <target> {}", env::current_exe().unwrap().to_str().unwrap()); process::exit(1); } // run let bat_cmd = find_bat_cmd(); if bat_cmd.is_none() { eprintln!(".bat or .cmd file is not found in {} env", PATHEXT); process::exit(1); } let mut cmd: Child = Command:...
Rust
0
.].len(), header.len); String::from_utf8(buf[hdr_len..].to_owned()).unwrap() } } #[test] fn test_thin_string() { let s = "hello there"; let fat_string = String::from(s); let mut thin_string = PackedBox::new(fat_string); let hdr_len = mem::size_of::<usiz...
Rust
0
ckpt_path = os.path.join(ckptdir, "last.ckpt") trainer.save_checkpoint(ckpt_path) def divein(*args, **kwargs): if trainer.global_rank == 0: import pudb; pudb.set_trace() import signal signal.signal(signal.SIGUSR1, melk) ...
Python
1
ngs::ts3client_initClientLib( &callbacks, ptr::null(), bindings::LogTypes::LogType_NONE, ptr::null(), res_path.as_ptr(), ); if err != (bindings::Ts3ErrorType::ERROR_ok as raw::c_uint) { ...
Rust
0
[P::Field], out_shares: &[P::Field], inp_mac_shares: &[P::Field], inp_rands: &[P::Field], rng: &mut RNG, ) -> Result<Vec<Wire>, MpcError> { // TODO: Generate triples in background during linear layers let modulus_bits = <P::Field as PrimeField>::size_in_bits(); ...
Rust
0
import numpy as np class TonemapHDR(object): """ Tonemap HDR image globally. First, we find alpha that maps the (max(numpy_img) * percentile) to max_mapping. Then, we calculate I_out = alpha * I_in ^ (1/gamma) input : nd.array batch of images : [H, W, C] output : nd.array batch of ...
Python
1
sync::Ready((item, self.req.take().unwrap()))), Err(err) => Err(FramedError { err: err.into(), framed: self.req.take().unwrap().into_parts().1, }), } } } macro_rules! factory_tuple ({ ($(($nex:tt, $Ex:ident)),+), $(($n:tt, $T:ident)),+} => { impl<...
Rust
0
.or_else(|| b.osm_tags.get("building:levels")) .and_then(|x| x.parse::<usize>().ok()) .unwrap_or(1); // For multi-story garages, assume every floor has the same capacity. Guess // 1 spot per 30m^2. ...
Rust
0
parsed_shortcode { Ok(_) => { panic!("A short code encoding an out-of-range value was successfully parsed."); }, Err(e) => { assert_eq!(format!("{}", e), "Error: The row offsets number appeared to be invalid.".to_string())} } } /// Attempt to parse a code with an invalid CRC. #[test] fn parse_inva...
Rust
0
}} ENUM!{enum D3D11_VPIV_DIMENSION { D3D11_VPIV_DIMENSION_UNKNOWN = 0, D3D11_VPIV_DIMENSION_TEXTURE2D = 1, }} STRUCT!{struct D3D11_TEX2D_VPIV { MipSlice: UINT, ArraySlice: UINT, }} STRUCT!{struct D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC { FourCC: UINT, ViewDimension: D3D11_VPIV_DIMENSION, Text...
Rust
0
s.append(np.array(ext[:3], dtype=np.float32)) else: extrinsics.append(np.eye(3, 4, dtype=np.float32)) intr = cam_data.get('intrinsic', [[500, 0, 259], [0, 500, 259], [0, 0, 1]]) if isinstance(intr, list) and len(intr) >= 3: intrinsics.append(np.array(...
Python
1
[`Module`]. pub unsafe fn call2_unprotected<'base, 'borrow>( self, _: Global<'base>, arg0: Value<'_, 'borrow>, arg1: Value<'_, 'borrow>, ) -> CallResult<'base, 'borrow> { let func = jl_get_kwsorter(self.func.datatype().expect("").ptr().cast()); let args = &mut [s...
Rust
0
ort_key, show_label=show_label, completed=completed, refresh_per_second=getattr(cli_args, "refresh_per_second", 10), simple=getattr(cli_args, "simple_progress", False), ) as loading_bar: additional_kwargs = { ...
Python
1
get(url) .send() .map_err(|x| format!("network error on sending: {}", x))?; let mut bytes = Vec::new(); res.read_to_end(&mut bytes) .map_err(|x| format!("network error on reading: {}", x))?; let demo = hldemo::Demo::parse_without_frames(&bytes...
Rust
0
s.shopify_toolkit.ShopifyShopRepository'), \ patch('app.tools.shopify_toolkit.AgentShopifyConfigRepository') as mock_config_repo_class: # Configure config repo to return disabled config mock_config_repo = MagicMock() mock_config_repo_class.return_value = mock_config_repo ...
Python
1
#configuration profil & système #----- CRÉER UN PROFIL ------ def creer_profil(): print("----CRÉATION PROFIL----") nom = input("Entrez votre nom : ") prenom = input("Entrez votre prénom : ")
Python
1
eauty'}, {'id': 12577, 'cat_info': ['a blue and yellow damselfish of Bermuda and Florida and the West Indies'], 'novel': False, 'name_zh': '雀鲷 小热带鱼', 'name': 'beaugregory'}, {'id': 12578, 'cat_info': ['an anemone fish of the genus Amphiprion'], 'novel': True, 'name_zh': '小丑海葵鱼', 'name': 'clown anemone fish'}, {'id': 12...
Python
1
target_values], [cost, pseudo_cost, network_output], updates=updates) validate = theano.function([l_in.input_var, target_values], [cost, network_output]) predict = theano.function([l_in.input_var], network_output) # ## Network Training #### Training Network #### print("Training network ...") num_batches_train = int(n...
Python
1
base distinguishes between their null type and JSON null. ); /// Contains all capabilities that the connector is able to serve. #[derive(Debug)] pub struct ConnectorCapabilities { pub capabilities: Vec<ConnectorCapability>, } impl ConnectorCapabilities { pub fn empty() -> Self { Self { capabilities: v...
Rust
0
uint,str> { * if x == uint::max_value { return err("overflow"); } * else { return ok(x+1u); } * } * map(~[1u, 2u, 3u], inc_conditionally).chain {|incd| * assert incd == ~[2u, 3u, 4u]; * } */ #[inline(always)] pub fn map_vec<T,U:Copy,V:Copy>( ts: &[T], op: fn(&T) -> Result<...
Rust
0
about available fields see [wutr](wutr) module"] pub type WUTR = crate::Reg<u32, _WUTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _WUTR; #[doc = "`read()` method returns [wutr::R](wutr::R) reader structure"] impl crate::Readable for WUTR {} #[doc = "`write(|w| ..)` method takes [wutr::W](wutr::W) writer struct...
Rust
0
ngStrategy::new(); let session = TcpSessionBuilder::new(lb, cluster_config) .with_reconnection_policy(Arc::new(NeverReconnectionPolicy::default())) .build(); session .query( "CREATE KEYSPACE IF NOT EXISTS test_ks WITH REPLICATION = { \ ...
Rust
0
# Copyright (C) 2013 Stratosphere Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
Python
1
#-*- coding:utf-8 -*- # Copyright (c) Kang Wang. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # mail: nessessary@qq.com """关于boll分仓策略的实现 只做上升通道, 下降通道暂时不做 1. 正负交易只做一次 2. 回撤到均线时就要回补, 用大的量来弥补 3. 超过限额就不要做波动了 """ import sys from autoxd.strategy ...
Python
1
{ unimplemented!() } }; replica_count = 2; check_volumes(&cluster, vol_cli, &volumes).await; } async fn check_volumes( cluster: &Cluster, vol_cli: &dyn volumes_api::tower::client::direct::Volumes, volumes: &[models::Volume], ) { ...
Rust
0
{ "timestamp": self.start_time.isoformat(), "environment": self.config['ENVIRONMENT'], "index_name": self.config['INDEX_NAME'], "mode": "FULL" if is_full else "INCREMENTAL", "reason": reason, "success": success, "duration_seconds": roun...
Python
1
e_mocks=False, ) # get the information about the report response = requests.get( api_url_for( rotkehlchen_api_server, 'historyactionableitemsresource', ), ) result = assert_proper_sync_response_with_result(response=response, status_code=HTTPStatus.OK) ...
Python
1
acruzError::BadInput => write!(f, "BadInput"), VeracruzError::InvariantFailed => write!(f, "InvariantFailed"), VeracruzError::ResultAlreadyWritten => write!(f, "ResultAlreadyWritten"), VeracruzError::ServiceUnavailable => write!(f, "ServiceUnavailable"), } } } /// Serial...
Rust
0
from .common import InfoExtractor from ..utils import unified_strdate class DFBIE(InfoExtractor): IE_NAME = 'tv.dfb.de' _VALID_URL = r'https?://tv\.dfb\.de/video/(?P<display_id>[^/]+)/(?P<id>\d+)' _TEST = { 'url': 'http://tv.dfb.de/video/u-19-em-stimmen-zum-spiel-gegen-russland/11633/', '...
Python
1
outbound pacemaker timeouts").unwrap(); /// Count of the pending new round events. pub static ref PENDING_NEW_ROUND_EVENTS: IntGauge = register_int_gauge!("libra_consensus_pending_new_round_events", "Count of the pending new round events.").unwrap(); /// Count of the pending sync info messages. pub static ref PENDIN...
Rust
0
std::fs; use std::iter::Peekable; use std::vec::IntoIter; use anyhow::Result; use crate::token::Token; use crate::token::{ ALL, ASSIGN, BLOCK, CLOSE_CBRACK, FROM, NL, ON, OPEN_CBRACK, PASS, PORT, PROTO, REPLACE_PREFIX, TO, }; pub struct Lexer { buf: Peekable<IntoIter<char>>, } impl Lexer { pub fn f...
Rust
0
fn approx_eq(&self, rhs: &Mat4, tol: Scalar) -> bool { self.data .iter() .zip(rhs.data.iter()) .all(|(x, y)| (x - y).abs() <= tol) } } impl fmt::Debug for Mat4 { #[cfg_attr(rustfmt, rustfmt_skip)] fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { ...
Rust
0
from mage_ai.api.oauth_scope import OauthScope from mage_ai.api.operations import constants from mage_ai.api.policies.BasePolicy import BasePolicy from mage_ai.api.presenters.LogPresenter import LogPresenter from mage_ai.data_preparation.models.pipeline import Pipeline from mage_ai.data_preparation.repo_manager import ...
Python
1
lf) -> None: if self.get_current_search_states() != self.search_states \ or self.search_results_length == 0: self.on_search_entry_activated(self.search_entry) return if self.search_results_length == 0: return replace_with = self.replace_entry...
Python
1
from engine.model.layout import Layout from .intersection import * class GraphCreater(object): def __init__(self, fileName): self.layout = Layout(fileName) def run(self): data = self.layout.getIntersectionData() self.interDict = self.getInterDict(data) self.edgeDict =...
Python
1
import requests import subprocess import time while True: try: r=requests.get('https://www.google.com/') subprocess.call(['python','main.py']) subprocess.call(['python','report_gen.py']) break except requests.exceptions.ConnectionError: print("No Internet: Retrying after...
Python
1
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Yujin Robot # 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 r...
Python
1
SAND: u32 = 15u32; #[doc = "*Required features: `\"Win32_Globalization\"`*"] pub const LOCALE_STIME: u32 = 30u32; #[doc = "*Required features: `\"Win32_Globalization\"`*"] pub const LOCALE_STIMEFORMAT: u32 = 4099u32; #[doc = "*Required features: `\"Win32_Globalization\"`*"] pub const LOCALE_SUPPLEMENTAL: u32 = 2u32; #[...
Rust
0
"""Функции для вычисления метрик (IoU, NMS).""" import torch def compute_iou_3d(pred_bbox: torch.Tensor, gt_bbox: torch.Tensor) -> torch.Tensor: """ Вычисляет axis-aligned IoU для 3D боксов. Args: pred_bbox (torch.Tensor): Предсказанные боксы [..., N, 6] (cx, cy, cz, w, h, l). gt_bbox (to...
Python
1
new(0.0, 2.0, 1.0), epsilon = 1e-6); assert_relative_eq!(rgb1_2, Rgb::new(0.0, 1.0, 1.0), epsilon = 1e-6); assert_relative_eq!(rgb1_3, Rgb::new(0.0, 1.0, 0.5), epsilon = 1e-6); assert_relative_eq!(rgb1_4, Rgb::new(1.0, 1.0, 1.0), epsilon = 1e-6); let c2 = Hsi::new(Deg(180.0), 1.0, 0.7);...
Rust
0
video_path = video_path_var.get() start_time = start_time_var.get() end_time = end_time_var.get() encoder = encoder_var.get() if not video_path or not os.path.exists(video_path): messagebox.showerror("Error", "Please select a valid video file.") return ...
Python
1
# -*- coding: utf-8 -*- # pylint: disable=line-too-long,consider-using-f-string """Handover Acknowledge Flags ================================ .. module:: pcapkit.const.mh.handover_ack_flag This module contains the constant enumeration for **Handover Acknowledge Flags**, which is automatically generated from :class:`...
Python
1
}) } } <gh_stars>0 use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)] pub struct LegStreamCalculationPeriodBusinessCenterGrp { /// NoLegStreamCalculationPeriodBusinessCenters #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "40940")] pub ...
Rust
0
tput_root(&H256::from_trimmed_hex_str("10").unwrap()) .unwrap() ); } #[test] fn save_and_get_block() { let tmp_dir = tempfile::Builder::new() .prefix("save_and_get_block") .tempdir() .unwrap(); let db = RocksDB::open(tmp_dir, COLUM...
Rust
0
")] source_channel: String, /// The channel to which packages will be promoted #[structopt(name = "TARGET_CHANNEL")] target_channel: String, #[structopt(flatten)] auth_token: AuthToken, } /// Atomically demotes selected packages in a target channel #[derive(ConfigOpt, StructOpt)] #[structop...
Rust
0
self._audit_info.operator_app_name = operator_app_name return self def common_drawers(self, common_drawers: ApiAuditCommonDrawers) -> "AuditInfoBuilder": self._audit_info.common_drawers = common_drawers return self def audit_detail(self, audit_detail: AuditDetail) -> "AuditInfoBu...
Python
1
_data(data) # 执行回测 result = system.predictor.backtest(args.type, algorithm=args.algorithm, periods=args.periods) if result: print_backtest_result(result) else: print(f"无法执行{args.type}的回测") elif args.compare: ...
Python
1
TURE = 1 TARGET_TEMPERATURE_RANGE = 2 TARGET_HUMIDITY = 4 FAN_MODE = 8 PRESET_MODE = 16 SWING_MODE = 32 AUX_HEAT = 64 TURN_OFF = 128 TURN_ON = 256 # These SUPPORT_* constants are deprecated as of Home Assistant 2022.5. # Please use the ClimateEntityFeature enum instead. _DEPRECATED_SUP...
Python
1
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Python
1
from math import pi def radians(degree) : return pi/2*(degree/90.0) if __name__ == "__main__" : degree=90.0 print(radians(degree)) degree=180.0 print(radians(degree))
Python
1
#!/usr/bin/python3 import sys for i in range(1, len(sys.argv)): print(sys.argv[i])
Python
1
{}", alt.text()).as_str(); } content } fn transpile(&mut self, transpiler: &mut Transpiler) -> String { let condition = &self.condition.transpile(transpiler); let consequence = &self.consequence.transpile(transpiler); let alternative = &self .alternative .as_ref() .unwrap()...
Rust
0
lid code unit in the original string. //! ``` //! # let bytes = [0x41, 0x42, 0x43]; //! # let string = string_inspector::DecodedString::decode(&bytes, encoding::all::ISO_8859_2).unwrap(); //! assert_eq!(3, string.atoms.len()); //! ``` //! //! Atoms can be easily converted to their character representation or byte repre...
Rust
0
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
Python
1
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from adapter.api.base import DataAPI from adapter.api.modules.utils import add_esb_info_before_request from config.domains import CC_APIGATEWAY_ROOT_V2 class _CCApi(object): MODULE = _("配置平台") def __init__(self): self.s...
Python
1
metrics: vec![], } } pub fn with_metrics(metrics: Vec<AggregatedMetric>) -> AggregatedMetrics { AggregatedMetrics { metrics: metrics, } } pub fn aggregate_counts<'a, I>(&mut self, counts: I) where I: Iterator<Item=(&'a Dimension, &'a u64)> { ...
Rust
0
from typing import ( Any, List, Literal, Mapping, Optional, Type, TypeVar, Union, overload, ) from booktracker.common.base_model import BaseModel ModelT = TypeVar("ModelT", bound=BaseModel) RecordT = Mapping[str, Any] ExcludeT = Optional[List[str]] class Hydrator: """ Res...
Python
1
# + | + # 6+-+-----+ # 8+-+-----+ x_edges = np.array([0, 2, 8]) y_edges = np.array([0, 6, 8]) relative_areas = np.array([ [3, 9], [1, 3]]) # ensure the number of points in each region is proportional to its area x = np.arra...
Python
1
) # if i == end: # torch.cuda.synchronize() # time_end = time.time() with torch.no_grad(): outputs = batch_processor( model, data_batch, train_mode=False, local_rank=args.local_rank, ) for output in outputs: token = ou...
Python
1
ting devices, and attach ! devices = MultitouchSupport.MTDeviceCreateList() num_devices = CFArrayGetCount(devices) for i in range(num_devices): device = CFArrayGetValueAtIndex(devices, i) # create touch dict for this device data_id = str(device) se...
Python
1
pub fn nvgTextGlyphPositions( ctx: *mut NVGcontext, x: c_float, y: c_float, string: *const c_char, end: *const c_char, positions: *mut NVGglyphPosition, maxPositions: c_int, ) -> c_int; pub fn nvgTextMetrics( ctx: *mut NVGcontext, ascender...
Rust
0
import math c = (math.sqrt(19)) print(f"{c:.1f}") c = round(c*10)/10 print(c)
Python
1
#!/usr/bin/env python import roslib roslib.load_manifest('learning_tf') import rospy import math import tf import geometry_msgs.msg import turtlesim.srv if __name__ == '__main__': rospy.init_node('turtle_tf_listener') listener = tf.TransformListener() rospy.wait_for_service('spawn') spawner = rospy...
Python
1
ef imshow(img) -> None: npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.axis("off") plt.tight_layout() plt.show() dataiter = iter(datamodule.val_dataloader()) images, labels = next(dataiter) routine.eval() logits = routine(images).reshape(8, 128, 10) # num_estimators, batch_si...
Python
1
import ply.lex as lex tokens = ( 'LANGLE', # < 'LANGLESLASH', # </ 'RANGLE', # > 'SLASHRANGLE', # /> 'EQUAL', # = 'STRING', # "144" 'WORD', # 'Welcome' in "Welcome to my webpage." ) t_ignore = ' \t\v\r' # shortcu...
Python
1
method:ident> $prefix:ident $(<$op:ident>)? $field:ident / $rename:ident / :$ty:ty$([$($new_tt:tt)*])?) => { $crate::util::expand_one_row!($method $(#[$outer])* $prefix $(<$op>)? $field / $rename / :$ty $([$($new_tt)*])? ); }; ($(#[$outer:meta])* <$method:ident> $prefix:ident $(<$op:ident>)? $field:iden...
Rust
0
import os import cv2 import numpy as np # the path mnist_path = "./" # number of images num_images_to_use = 300 # Create empty lists to store image vectors and corresponding labels image_vectors = [] labels = [] # Go through each digit folder for digit in range(10): digit_folder_path = os.path.join(mnist_path...
Python
1
t is not specified, the default value is 610 seconds. For global external Application Load Balancers, the minimum allowed value is 5 seconds and the maximum allowed value is 1200 seconds. """, ) def AddClearHttpKeepAliveTimeoutSec(parser): """Adds the http keep alive timeout sec argument.""" p...
Python
1
the build.sh script so that the project can be built successfully. {LANGUAGE_SPECIFICS} ### Provided Resources - Dockerfile: <dockerfile> {DOCKERFILE} </dockerfile> - Build script <build_script> {BUILD_SCRIPT} </build_script> - Initial failed build output: <logs> {LOGS} </logs> ### Interaction P...
Python
1
from django.urls import path from .views import analyse_nombre_api, nombres_api urlpatterns = [ path('analyse-nombre/', analyse_nombre_api, name='analyse-nombre-api'), path('nombres/', nombres_api, name='nombres-api'), ]
Python
1
s() { trace_init(); let logs: Vec<String> = random_lines(100).take(10).collect(); test_event( None, None, None, None, logs.join("\n").into_bytes(), logs, Errored, ) .await; } #[tokio::t...
Rust
0
s not None: custom_xkey.set_iv(args.hexiv) if self.xkey is None: if args.b64key: # 如果解析后没有密钥相关信息 # 而命令行又指定了 也进行设定 self.set_segments_key(custom_xkey) return if self.xkey.method and self.xkey.method.upper() in ['SAMPLE...
Python
1
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Pretrained retrieval model on the Wizard of Wikipedia dialogue task. """ from parlai.core.build_data import download_...
Python
1
import os import tempfile from pathlib import Path import pytest from ebooklib import epub from reportlab.pdfgen import canvas from audify.readers.pdf import PdfReader MODULE_PATH = Path(__file__).resolve().parents[2] @pytest.fixture def pdfs() -> list[str]: # PDF file in english tmp_folder = tempfile.temp...
Python
1
.collect::<Vec<Value>>(), ); let meta: AITensorMeta<T, S> = AITensorMeta::<T, S>::from_redis_value(&meta_part).unwrap(); let mut blob_part_iter = it.skip(4); let blob = match (blob_part_iter.next(), blob_part_iter.next()) { (Some(_blob_field), Some(blob)) => { ...
Rust
0
elConstants.RADAR_TRACKS_WIDTH] = [track.dRel, track.yRel, track.vRel] # tracked dropped frames vipc_dropped_frames = max(0, meta_main.frame_id - last_vipc_frame_id - 1) frames_dropped = frame_dropped_filter.update(min(vipc_dropped_frames, 10)) if run_count < 10: # let frame drops warm up frame_d...
Python
1
println!( "tree product: {}", tree_counts.iter().fold(1, |acc, c| acc * c) ); } } #[allow(dead_code)] enum Move { Up(u32), Right(u32), Down(u32), Left(u32), } struct Movement { moves: Vec<Move>, } impl Movement { fn with_moves(moves: Vec<Move>) -> Mov...
Rust
0
bindgen] pub struct DaedalusWallet(PrivateKey); #[wasm_bindgen] impl DaedalusWallet { pub fn new(key: PrivateKey) -> DaedalusWallet { DaedalusWallet(key) } pub fn master_key(&self) -> PrivateKey { self.0.clone() } pub fn recover(entropy: &Entropy) -> Result<DaedalusWallet, JsValue>...
Rust
0
a=0.7 ) axes[1].set_xlabel("LDA Component 1") axes[1].set_ylabel("LDA Component 2") axes[1].set_title("LDA Projection") axes[1].legend(title="Orientation", loc="best") else: axes[1].hist(X_lda[:, 0], bins=30, color='gray', alpha=0.7) axes[1].set_xlabel("LD...
Python
1
ec<u8>) -> Result<(), std::io::Error> { buffer.write_all(b"\"")?; buffer.write_all(string_val.as_bytes())?; buffer.write_all(b"\"") } /// Writes `json_array` and its contents to `buffer`, with the array indented `indent` times fn format_array(json_array: &Vec<Value>, buffer: &mut Vec<u8>, indent: usize) ->...
Rust
0
, this functions returns `Ok(-1)` /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor). /// /// This function uses `T: From<i32>` instead of `i32` directly because some IO related /// functions return different integer types (like `read`, that returns an `i64`) fn get_hand...
Rust
0