text
string
label_name
string
labels
int64
o, //! except for the fill character. //! //! # Examples //! //! ``` //! use rt_format::{Format, FormatArgument, ParsedFormat, Specifier}; //! use std::cmp::PartialEq; //! use std::convert::TryInto; //! use std::fmt; //! //! #[derive(Debug, PartialEq)] //! pub enum Variant { //! Int(i32), //! Float(f64), //! ...
Rust
0
, b: &Value) { match (a, b) { (&mut Value::Object(ref mut a), &Value::Object(ref b)) => { for (k, v) in b { merge(a.entry(k.clone()).or_insert(Value::Null), v); } } (a, b) => { *a = b.clone(); } } } <reponame>ultrasaurus/rust-clib use std::ffi::c_void; use tokio::runtime::Runtime; use tokio::net:...
Rust
0
Vec<bool>) { if ptr.is_null() { return; } unsafe { Box::from_raw(ptr); } } #[no_mangle] pub extern "C" fn array_deinit_string(ptr: *mut Vec<*mut BString>) { if ptr.is_null() { return; } unsafe { Box::from_raw(ptr); } } #[no_mangle] pub extern "C" fn box...
Rust
0
import pytest from ariadne.wsgi import GraphQLMiddleware def test_initializing_middleware_without_path_raises_value_error(schema): with pytest.raises(Exception) as excinfo: GraphQLMiddleware(lambda *_: None, schema, path="") assert isinstance(excinfo.value, ValueError) assert excinfo.value.args[...
Python
1
(to_binary(&contract_address)?) } QueryMsg::PhaseId => { let phase_id = CURRENT_PHASE.load(deps.storage)?.id; Ok(to_binary(&phase_id)?) } QueryMsg::PhaseAggregators { phase_id } => { let contract_address = PHASES.load(deps.storage, phase_id.into())?; ...
Rust
0
for complete details on how `#[repr(C)]` enums are defined. /// /// There are two different representations for tagged unions. /// See [TaggedUnionStyle] for details. TaggedUnion(&'static TaggedUnionDef), /// A C-style enum, without any data. /// /// See [TypeInfo::TaggedUnion] for enums *w...
Rust
0
et_total_snowheight() _TOTALHEIGHT = GRID.get_total_height() _NLAYERS = GRID.get_number_layers() _new_snow_height, _new_snow_timestamp, _old_snow_timestamp = GRID.get_fresh_snow_props() _LAYER_HEIGHT = np.array(max_layers * [np.nan]) _LAYER_RHO = np.array(max...
Python
1
), )?, Err(RealError::Nan) => self.state.error( arg_loc, format!("超出 LOG 函数的定义域。参数值是:{}", value), )?, } } SysFuncKind::Mid => { let len = if arity.get() == 3 { self.pop_u8(false)? as usize } else { 255 ...
Rust
0
users_by_shell = {} with open("../DATA/passwd") as passwd_in: for line in passwd_in: shell = line.rstrip().split(":")[-1] # or # *_, shell = line.rstrip().split(":") if shell == "": shell = "NONE" if shell not in users_by_shell: users_by_shell[shell] ...
Python
1
PROMPT.format(user_issue, diffstuff), "execution_trace_pre": execution_trace_pre, "execution_trace_post": execution_trace_post, "unittest_patch": patch, "instance_id": instance_id + "_seed=" + str(seed), } new_examples.append(new_e...
Python
1
import os import logging from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.models import Base from app.database import engine from app.routes import dashboard_route, files_route, tickets_route logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) app = Fast...
Python
1
from . import test_ddmrp_warning
Python
1
, }, seed: editor_state.frame_to_seconds(editor_state.current_frame()), }; common.frame_data_buffer.upload(devcon, common.frame_data); let mut clip_map_map = HashMap::new(); for track in timeline.tracks.iter_mut() { for clip in track.clips.iter_mut() ...
Rust
0
retty_env_logger; #[macro_use] extern crate log; mod base; use base::*; fn main() { cluster_init!(); kaostest!("epidemic-periodic-index-fp", { ap_events_check_node_spawn!(node1); ap_events_check_node_spawn!(node2); ap_events_check_node_spa...
Rust
0
) # Create toolset WITH toolset-level transformers toolset_with_toolset_transformers = YAMLToolset( name="kubernetes/core", tags=[ToolsetTag.CORE], description="Kubernetes toolset with toolset-level transformers", tools=[kubectl_describe], # KEY DIFFERENCE: Has toolset...
Python
1
).unwrap(); val[0] as i32 % max + min } #![ warn( rust_2018_idioms ) ] #![ warn( missing_debug_implementations ) ] #![ warn( missing_docs ) ] // #![ feature( type_name_of_val ) ] // #![ feature( trace_macros ) ] // use test_tools::*; use instance_of as TheModule; #[ allow( unused_imports ) ] use test_tools::*; t...
Rust
0
# Those are the field names of the cargo tables of leaguepedia # Tournament tournaments_fields = { "Name", "DateStart", "Date", "Region", "League", "Rulebook", "TournamentLevel", "IsQualifier", "IsPlayoffs", "IsOfficial", "OverviewPage", } # Game game_fields = { "GameId...
Python
1
class Solution: def addBinary(self, a: str, b: str) -> str: a1=int(a,2) b1=int(b,2) return bin(a1+b1)[2:]
Python
1
vec![ (FirstLayerEvent::LineStatsFailure(data.channel_token.take().unwrap())).wrap().into(), ]); */ } } struct OnChannelEstablished; impl TransitionHandle for OnChannelEstablished { type DataType = LineStatsData; type SignalType = LineStatsSignals; fn call(&self, input: &(), data: &mut Self::Data...
Rust
0
{ GENCTRL7R::GCLK0 => 1, GENCTRL7R::GCLK1 => 2, GENCTRL7R::GCLK2 => 4, GENCTRL7R::GCLK3 => 8, GENCTRL7R::GCLK4 => 16, GENCTRL7R::GCLK5 => 32, GENCTRL7R::GCLK6 => 64, GENCTRL7R::GCLK7 => 128, GENCTRL7R::GCLK8 => ...
Rust
0
import os import sys import time sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../'))) from sphero_sdk import SpheroRvrObserver from sphero_sdk import InfraredCodes from sphero_sdk import RawMotorModesEnum rvr = SpheroRvrObserver() def main(): """ This program sets up RVR to co...
Python
1
// unsafe { TODO: call ffi:ges_timeline_element_remove_child_property() } //} fn ripple(&self, start: gst::ClockTime) -> Result<(), glib::error::BoolError> { unsafe { glib::result_from_gboolean!( ffi::ges_timeline_element_ripple(self.as_ref().to_glib_none().0, start.int...
Rust
0
ow >= BOARD_SIZE { println!( "Position out of bounds of board. Input: {:?}, actual board size: {}", position, BOARD_SIZE ); Err(()) } else { let action = TicTacToeAction(position); Ok(act...
Rust
0
m(self.style.text_size), color: text_color, font: self.font, horizontal_alignment: Horizontal::Left, vertical_alignment: Vertical::Center, }); } } } impl<'a, T, Message, Renderer> From<List<'a, T, Message, Renderer>> for Elemen...
Rust
0
ll_with_args<Args: Copy>(&self, args: Args) where F: Clone + RegistryFnCall<Args> { self.clear_unused_callbacks(); // The clone is performed in order for the callbacks to be able to register new ones. let callbacks = self.callback_list.borrow().clone(); callbacks.iter().for_each(move...
Rust
0
ne] = [None] * ( self.num_layers + 1 ) # +1 for top (always None) self.counter = 0 @override def step(self, observation: Tensor) -> Tensor: """Performs a step through the hierarchical agent, propagating actions and rewards through each layer. Args: ...
Python
1
ain_path.replace('aux','train'),split) test_X = get_features(train_path, split) #assert train_X.flags.c_contiguous gc.collect() if mem: print 'mem usage after getting features '+str(mem.usage()) assert train_X.shape[0] == 50000 assert train_y.shape == (50000,) assert str(train_X.dt...
Python
1
_equal(node0.last_message["reject"].data, block.sha256) del node0.last_message["reject"] self.log.info("Test that invalid-according-to-cltv transactions cannot appear in a block") block.nVersion = 4 spendtx = create_transaction(self.nodes[0], self.coinbase_blocks[1], ...
Python
1
* Hp / H)) bw_p = int(round(mw * Wp / W)) mask_px[:, :, top_p:top_p+bh_p, left_p:left_p+bw_p] = 1.0 # If outpainting, need to invert (outside=1, inside=0 is the masked region) if mask_mode == "outpainting": mask_px = 1.0 - mask_px if downsample_mode not in ("nearest", "area", "bilin...
Python
1
r(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() el...
Python
1
(x: 3.0, y: 2.0) ]; let mls = MultiLineString(vec![v1, v2]); let correct = vec![ Coordinate::from((4.0, 0.0)), Coordinate::from((4.0, 4.0)), Coordinate::from((3.0, 2.0)), Coordinate::from((3.0, 1.0)), Coordinate::from((0.0, ...
Rust
0
size_after = p/100 * (size_used + unused) // which equals (1 - p/100) * unused <= p/100 * size_used LimitOption::Percentage(p) => (p * self.stats.size.used) / (100 - p), }; let max_repack = match max_repack { LimitOption::Unlimited => u64::MAX, LimitOpti...
Rust
0
import os import requests org = 'excaliburjs' token = os.getenv('GH_TOKEN') start_date = '2024-01-01' end_date = '2024-12-31' headers = {'Authorization': f'token {token}'} # Get all repositories in the organization repo_url = f'https://api.github.com/orgs/{org}/repos' repos = requests.get(repo_url, headers=headers)....
Python
1
let root_area = BitMapBackend::new(file_name, (1024, 768)).into_drawing_area(); root_area.fill(&WHITE)?; let mut chart = ChartBuilder::on(&root_area) .margin::<u32>(20) .caption(title, ("sans-serif", 40).into_font()) .x_label_area_size::<u32>(30) .y_label_area_size::<u32>(30) ...
Rust
0
, second, millisecond)) .flatten() .collect::<Vec<Time>>(); set.sort_by_key(|a| a.time()); set } pub fn mtimeset(&self, hour: usize, minute: usize, _: usize, millisecond: usize) -> Vec<Time> { let mut set = self .options .bysecond ...
Rust
0
import time from selenium import webdriver from selenium.webdriver.common.by import By def setup(): from selenium.webdriver.chrome.service import Service serv_obj=Service("C:\Python_Selenium\Drivers\chromedriver-win64\chromedriver.exe") driver=webdriver.Chrome(service=serv_obj) return driver my_driver...
Python
1
OverkizCommand.SET_DEROGATION, temperature, OverkizCommandParam.FURTHER_NOTICE, ) await self.executor.async_execute_command( OverkizCommand.SET_MODE_TEMPERATURE, OverkizCommandParam.MANUAL_MODE, temperature, ) await self....
Python
1
loader::load_integer_row_list("../day/02/input.csv")[0]); let actual = input::find_cent(&comp, 6_627_023).expect("should have a value"); let expected = input::Input::new(12, 2).cent(); assert_eq!(actual, expected); } } <reponame>tommilligan/cargo-raze<filename>examples/vendored/complicated_cargo_library/...
Rust
0
plicitPromote<T>, <T as ImplicitPromote<$rust_type>>::Output: HasAfEnum, { type Output = Array<<T as ImplicitPromote<$rust_type>>::Output>; fn $op_name(self, rhs: $rust_type) -> Self::Output { let op2 = constant(rhs, self.dims()); self.$op_nam...
Rust
0
else { (start_index - 1)..end_index }; for index in range { lines.swap(index, index + 1); } } pub(crate) fn swap_range_down(lines: &mut Vec<Line>, start_index: usize, end_index: usize) { let range = if end_index <= start_index { end_index..=start_index } else { start_index..=end_index }; for index in ...
Rust
0
f } } #[doc = "Bits 0:1 - 1:0\\] 00: No action 01: PM1 10: PM2 11: PM3"] #[inline(always)] pub fn pm(&mut self) -> PM_W { PM_W { w: self } } } use path_builder::SvgBuilder; use core::math::vec2; pub fn build_logo_path<Builder: SvgBuilder>(path: &mut Builder) {; path.move_to(vec2(122.631...
Rust
0
import psutil from utils.features import ConnectionFeature def crawl_connections(): created_since = -1 proc_list = psutil.process_iter() for p in proc_list: pid = (p.pid() if hasattr(p.pid, '__call__') else p.pid) status = (p.status() if hasattr(p.status, '__call__' ...
Python
1
""" Program to checks whether a number is an **Armstrong number**. An **Armstrong number** (also called a narcissistic number) is a number that is equal to the sum of its digits each raised to the power of the number of digits. Examples: - 153 is an Armstrong number because: 1³ + 5³ + 3³ = 153 - 9474 is an Ar...
Python
1
it_m.ident ); if let TypeError::Mutability = terr { if let Some(trait_err_span) = trait_err_span { if let Ok(trait_err_str) = tcx.sess.source_map().span_to_snippet(trait_err_span) { diag.span_suggestion( ...
Rust
0
hm.insert(Keycode::Q, 0x7); hm.insert(Keycode::W, 0xA); hm.insert(Keycode::A, 0x4); hm.insert(Keycode::Z, 0x5); hm.insert(Keycode::X, 0x0); } } assert_eq!(hm.len(), 16); hm } <gh_stars>1-10 /** This attribute generates an ffi-safe trait ...
Rust
0
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn from mmcv.cnn import ConvModule from mmseg.ops import Upsample from ..builder import HEADS from .decode_head import BaseDecodeHead @HEADS.register_module() class SETRMLAHead(BaseDecodeHead): """Multi level feature aggretation head...
Python
1
if !(c_to_t || t_to_c || a_to_g || g_to_a) { continue; } let chrom = snp::get_chrom_name(this.rid(), &hv)?; let seq = snp::get_chrom(chrom, &genome)?; let this_pos = this.pos() as usize; let next_pos = if c_to_t || t_to_c { this_pos + 1 }...
Rust
0
(Factor), } impl EvalT for Expression2 { fn eval(&self) -> u64 { match self { Expression2::Mul(lhs, rhs) => lhs.eval() * rhs.eval(), Expression2::Factor(factor) => factor.eval(), } } } #[derive(Debug, Clone)] enum Factor { Add(Box<Factor>, Atom<Expression2>), Atom(Atom<Expression2>), } impl EvalT for Fact...
Rust
0
file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2016 The developers of bearssl-sys. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/bearssl-sys/master/COPYRIG...
Rust
0
}, ... }, ... ] >>> pd.json_normalize(data, max_level=1) id name fitness.height fitness.weight 0 1.0 Cole Volk 130 60 1 NaN Mark Reg 130 60 2 2.0 Faye Raker 130 60 >>> data = [ ... ...
Python
1
OP_Vphaddbw_xmm_xmmm128 = 4156, /// `VPHADDBD xmm1, xmm2/m128` /// /// `XOP.128.X9.W0 C2 /r` /// /// `XOP` /// /// `16/32/64-bit` XOP_Vphaddbd_xmm_xmmm128 = 4157, /// `VPHADDBQ xmm1, xmm2/m128` /// /// `XOP.128.X9.W0 C3 /r` /// /// `XOP` /// /// `16/32/64-bit` XOP_Vphaddbq_xmm_xmmm128 = 4158, /// `VPHA...
Rust
0
''' author : s1g0day Creat time : 2024/2/21 14:52 modification time: 2024/8/12 14:58 Remark : 指定socks文件 ''' from functools import wraps from aiohttp import web import json from ymicp_socks import beian # 跨域参数 corscode = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allo...
Python
1
from odoo import api, fields, models class AccountCommonJournalReport(models.TransientModel): _name = 'account.common.journal.report' _description = 'Common Journal Report' _inherit = "account.common.report" amount_currency = fields.Boolean('With Currency', help="Print Report with the currency column...
Python
1
import numpy as np import math def choose_stress_model(theta, lamb): # this function chooses which model of the stress should be used depending on the value of the strain # ORDER: nu=ln((1-phi)*mu), eta=ln(E*phi), tau=ln(a-1), xi=ln(c-a),chi=ln(b-c), phi_mu = theta[0] # this is actually phi_mu phi_E ...
Python
1
= [] dist.all_gather(object_size_list, local_size, group=group) max_object_size = int(max(object_size_list).item()) # type: ignore[type-var] input_tensor.reshape_(max_object_size) # TODO 暂时没有在 paddle 中发现类似 torch.distributed.gather 的函数 output_tensors = [] dist.all_gather(output_tensors, input_te...
Python
1
: Multiply Factor is 37"] _13, #[doc = "14: Multiply Factor is 38"] _14, #[doc = "15: Multiply Factor is 39"] _15, #[doc = "16: Multiply Factor is 40"] _16, #[doc = "17: Multiply Factor is 41"] _17, #[doc = "18: Multiply Factor is 42"] _18, #[doc = "19: Multiply Factor is...
Rust
0
l(Val::Percent(5.0)), justify_content: JustifyContent::Center, align_items: AlignItems::Center, ..Default::default() }, material: materials.add(Color::rgb_u8(40, 40, 40).into()), ..Default::default() }) .with_children(|p...
Rust
0
11100100, // y* 0b01001010, // z ]; /// Non-ASCII injective phone table. /// /// Starting at C1. const INJECTIVE_PHONES_C1: [u8; LETTERS_C1 as usize] = [ INJECTIVE_PHONES[(b's' - b'a') as usize] ^ 1, // ß INJECTIVE_PHONES[(b'a' - b'a') as usize] ^ 1, // à INJECTIVE_PHONES[(b'a' - b'a') as usize] ^ 1, /...
Rust
0
: \ {}, must be in range `1.0..=1500.0`", horizontal_accuracy, ); self.horizontal_accuracy = Some(horizontal_accuracy); self } /// Configures the direction in which the user is headed. The value must be /// in range `1..=360`. Reflects the `heading` paramet...
Rust
0
esult<Datum<'a>, EvalError> where T: TimestampLike, { neg_interval_inner(b).and_then(|i| add_timestamplike_interval(a, i)) } fn add_date_time<'a>(a: Datum<'a>, b: Datum<'a>) -> Datum<'a> { let date = a.unwrap_date(); let time = b.unwrap_time(); Datum::Timestamp( NaiveDate::from_ymd(date.ye...
Rust
0
model_checkpoint = ModelCheckpoint(filepath='best_model.h5', # Fixed filepath extension monitor='val_loss', save_best_only=True)
Python
1
Extend AABB let mut fat_aabb = B2AABB { lower_bound: aabb.lower_bound - r, upper_bound: aabb.upper_bound + r, }; // Predict AABB movement let d: B2vec2 = B2_AABB_MULTIPLIER * displacement; if d.x < 0.0 { fat_aabb.lower_bound.x += d.x; } else { fat_aabb.upper_bound.x += d.x; } if d.y < 0.0 { fat_aa...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ .. Licence MIT .. codeauthor:: Jan Lipovský <janlipovsky@gmail.com>, janlipovsky.cz """ import pytest @pytest.mark.parametrize( "text, expected", [ ( "URI with User info in Authority ftp://jan@example.com:123/test", ["ftp://jan...
Python
1
cursor.fetchone(): # Cria a tabela se não existir cursor.execute(''' CREATE TABLE auditoria ( id INTEGER PRIMARY KEY AUTOINCREMENT, acao TEXT NOT NULL, descricao TEXT, dados TEXT, ...
Python
1
rser).m_namespaceSeparator != 0 { len += 1; } if !(*parser).m_freeBindingList.is_null() { b = (*parser).m_freeBindingList; if len > (*b).uriAlloc as usize { let mut temp: *mut XML_Char = REALLOC!((*b).uri => [XML_Char; len + EXPAND_SPARE]); if temp.is_null() { ...
Rust
0
ecs::prelude::{Join, Read, ReadExpect, ReadStorage, System, SystemData, Write, WriteStorage}, }; use std::ops::Deref; /// This system is responsible for detecting collisions between balls and /// paddles, as well as balls and the top and bottom edges of the arena. #[derive(SystemDesc)] pub struct BounceSystem; im...
Rust
0
in 0..100000 { led0.set(); led1.set(); nop(); } for _ in 0..100000 { led0.clear(); led1.clear(); nop(); } } } <gh_stars>0 //#![feature(trace_macros)] #![allow(dead_code)] #![cfg_attr(feature = "cargo-clippy", allow(red...
Rust
0
let raw_payload = base64::decode(&req_body).expect("Unable to decode base64."); let response = utils::attempt_decode(&raw_payload, &charset).unwrap(); HttpResponse::Ok().body(response) } #[post("/decode_mime_header")] pub async fn decode_mime_header(req_body: String) -> impl Responder { let normalize...
Rust
0
offsets.as_i32x8(); macro_rules! call { ($imm8:expr) => { vpscatterdq(slice, mask, offsets, src, $imm8) }; } constify_imm8_gather!(scale, call); } /// Scatter 64-bit integers from src into memory using 64-bit indices. /// /// [Intel's documentation](https://software.intel.com/si...
Rust
0
r#" [project] name = "foo" version = "0.1.0" [dependencies] present_dep = "1.2.3" "#, ) .file("src/lib.rs", "") .build(); p.cargo("build").run(); let p2 = project() .at("bar") .file( ...
Rust
0
.spawn() .with_context(|| format!("Failed to execute {:?} {:?}", exe_name, args))?; } Ok(()) } /// Validate the scheme according to RFC3986 (https://datatracker.ietf.org/doc/html/rfc3986) fn parse_scheme(src: &str) -> Result<String, anyhow::Error> { let src = src.trim(); let m...
Rust
0
'], short = return_hashes['short'], size = filesize ) return khash class NoTransactionFound(Exception): """ No Transaction found in this job""" pass def find_khash(app: fantail.app, short: str = None, sha256: str = None):...
Python
1
io::{Read, Write}; use std::path::{Path, PathBuf}; use std::time::Instant; use clap::{App, Arg}; use ffmpeg::{format, media, frame}; use dfpwm::DFPWM; use rip::TrackMetadata; // Borrowed from https://github.com/meh/rust-ffmpeg/blob/master/examples/transcode-audio.rs fn get_filter(spec: &str, decoder: &ffmpeg::codec:...
Rust
0
from django.core.management.base import BaseCommand, CommandError from ui.models import Warc from ui.rabbit import RabbitWorker import json class Command(BaseCommand): help = 'Resends warc_created messages to the messaging service.' def add_arguments(self, parser): parser.add_argument("routing_key", ...
Python
1
max(self.time_points) if self.time_points else 0) } return stats def __repr__(self): stats = self.get_node_statistics() return (f"NodeLifecycleManager(total_nodes={stats['total_nodes']}, " f"active_nodes={stats['active_nodes']}, " f...
Python
1
An(MultiPass::<X::Size, f64>::new()) * dc(x) } /// Butterworth lowpass filter (2nd order). /// - Input 0: audio /// - Input 1: cutoff frequency (Hz) /// - Output 0: filtered audio #[inline] pub fn butterpass() -> An<ButterLowpass<f64, f64, U2>> { An(ButterLowpass::new(DEFAULT_SR, 440.0)) } /// Butterworth lowpass...
Rust
0
actor( mut ctx: actor::Context<!, ThreadLocal>, address: SocketAddr, server_ref: ActorRef<server::Message>, ) -> io::Result<()> { let stream = TcpStream::connect(&mut ctx, address)?.await?; let cpu = cpu_affinity(&stream).unwrap(); assert_eq!(cpu, 0); server...
Rust
0
import os from dotenv import load_dotenv load_dotenv() DB_USER = os.environ.get("DB_USER") DB_PASSWORD = os.environ.get("DB_PASSWORD") DB_PORT = os.environ.get("DB_PORT") DB_SERVICE_NAME = os.environ.get("DB_SERVICE_NAME") DB_HOST = os.environ.get("DB_HOST") MONGO_DB_NAME = os.environ.get("MONGO_DB_NAME") MONGO_DB_...
Python
1
message_accessor::<_, Argon2>( "kdf_argon", Encrypted::has_kdf_argon, Encrypted::get_kdf_argon, )); fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<GlobalKeyRef>>( ...
Rust
0
#!/usr/bin/env python # File: pa.py # This program prints out your system's audio input configuration as seen # by pyaudio (PortAudio). # Copyright 2013-2014 Martin Ewing import pyaudio as pa print """First, you will receive a number of ALSA warnings about unknown PCM cards, etc. This is an annoying but harmless f...
Python
1
rounds, remaining_hitpoints ); remaining_hitpoints.val() * rounds as i32 }, WinnerGoblins(remaining_hitpoints) => { debug!( "Goblins win after {} rounds with {} total hit points left!", rounds, remaining_hitpoints ...
Rust
0
self._Uin = params.get("Uin") self._CreateUin = params.get("CreateUin") memeber_set = set(params.keys()) for name, value in vars(self).items(): property_name = name[1:] if property_name in memeber_set: memeber_set.remove(property_name) if len...
Python
1
"""Utilities to work with pygls. Helper functions that simplify working with pygls """ from typing import Optional from lsprotocol.types import Position, Range from pygls.workspace import TextDocument def char_before_cursor( document: TextDocument, position: Position, default: str = "" ) -> str: """Get the...
Python
1
import numpy as np import matplotlib.pylab as plt from mpl_toolkits.mplot3d import Axes3D from colors import colors def convert_color_to_hexcode(rgb): r, g, b = rgb return '#%02x%02x%02x' % (int(r*255), int(g*255), int(b*255)) def render_pc_set(out_fn, pcs, \ subplotsize=(1, 1), figsize=(8, 8), azim=6...
Python
1
EmitType::*; match s { "unversioned-shared-resources" => Ok(Unversioned), "toolchain-shared-resources" => Ok(Toolchain), "invocation-specific" => Ok(InvocationSpecific), _ => Err(()), } } } impl RenderOptions { crate fn should_emit_crate(&self) -...
Rust
0
on, current_station: current_station, stops: stations_list} } } /// Struct that holds the train station data #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TrainStation { /// Three-charachters ID pub id: String, /// Trenitalia region ID pub region_id: u8, /// Tuple that contains lat...
Rust
0
"NOT", TILDE => "TILDE", AT => "AT", DOT => "DOT", DOTDOT => "DOTDOT", COMMA => "COMMA", SEMI => "SEMI", COLON => "COLON", MOD_SEP => "MOD_SEP", RARROW => "RARROW", LARROW => "LARROW", DARROW => "DARROW", FAT_ARROW => "FAT_...
Rust
0
s docParamNameSub class docXRefSectTypeSub(supermod.docXRefSectType): def __init__(self, id=None, xreftitle=None, xrefdescription=None): supermod.docXRefSectType.__init__(self, id, xreftitle, xrefdescription) supermod.docXRefSectType.subclass = docXRefSectTypeSub # end class docXRefSectTypeSub class doc...
Python
1
let datetimer = if time.len() == 10 { format!("{} 00:00:00", time.to_string()) } else { time.to_string() }; let datetime = datetimer.as_str(); let context = Context::new(self.event_id as u16); let ts = Timestamp::from_unix(&context, 1497624119, 1234); ...
Rust
0
native would be to use functools.partial >>> new_class = partial(cls, **kwargs) The issue is twofold: 1. the class doesn't have a name, so one would have to set it explicitly: >>> new_class.__name__ = new_name 2. the new class will be a functools object and one cannot inherit from it. Instead...
Python
1
cDoc::space()) .append(RcDoc::text("else")) .append(RcDoc::space()) .append(func_error(error_msg)) } fn func_assert_lt<'a>(var: &str, val: u32) -> RcDoc<'a> { func_assert(func_expr_lt(var, val), &format!("{} out of bounds", var)) } fn func_body<'a>(name: &str, rtype: &str, body: RcDoc<'a>)...
Rust
0
should be a hash"); let modified_balance_alpha: U512 = builder.get_purse_balance(default_account.main_purse()); let transferred_amount: U512 = U512::from(TRANSFER_AMOUNT); let payment_purse_amount = *DEFAULT_PAYMENT; // next make another deploy that USES stored payment logic let exec_request = { ...
Rust
0
ut unsafe { &mut *this_ptr.inner }.last_update; (*inner_val) } /// When the last known update to the node state was issued. /// Value is opaque, as set in the announcement. #[no_mangle] pub extern "C" fn NodeAnnouncementInfo_set_last_update(this_ptr: &mut NodeAnnouncementInfo, mut val: u32) { unsafe { &mut *this_ptr....
Rust
0
#!/usr/bin/env python3 # # Cyrius: CYP2D6 genotyper # Copyright (c) 2019-2020 Illumina, Inc. # # Author: Xiao Chen <xchen2@illumina.com> # # 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 ...
Python
1
ahoo_finance_api::{YResponse, YahooConnector, YahooError}; pub struct FetchActor<T: YahooFinanceApi, H: Handler<PerformanceData>> { sender: Addr<H>, yahoo_api: T, tickers: Vec<Ticker>, from: DateTime<Utc>, } impl<T: YahooFinanceApi, H: Handler<PerformanceData>> FetchActor<T, H> { pub fn new(sender...
Rust
0
import pandas as pd from .asv import ASV from utils import find_asv_model_checkpoint, save_yaml def evaluate_asv(eval_datasets, eval_data_dir, params, device, anon_data_suffix, model_dir=None): backend = params.get('backend', 'speechbrain').lower() if backend == 'speechbrain': return asv_eval_speechb...
Python
1
"]}', 'border-radius': '8px', 'margin': '5px' }) indicator_cards.append(card) return html.Div([ html.Div([ html.H5("📊 技術指標選擇", style={'color': '#00ff88'}), dbc.ButtonGroup([ dbc.Button("全選", id='btn-select-all', size='sm',...
Python
1
def get_acc(y,y_hat): acc = sum(1 for yi, yi_hat in zip(y, y_hat) if yi == yi_hat) / len(y) return round(acc, 3) def get_error(y,y_hat): return sum(yi != yi_hat for yi,yi_hat in zip(y,y_hat))/len(y) def get_precision(y,y_hat): TP = sum(1 for yi, yi_hat in zip(y, y_hat) if yi == 1 and yi_hat == 1) ...
Python
1
icer to use B or W instead of PIN, /// as then each pin could have just its own register to read /// and write to. This needs some work on the SVD. pub struct Gpio<D: Direction> { // pub(crate) b: RegClusterProxy<raw::gpio::B>, // pub(crate) w: RegClusterProxy<raw::gpio::W>, pub(crat...
Rust
0
" then only local variables will be searched for. """ resolve = _get_resolver(known, filenames, handle_id=handle_id, perfilecache=perfilecache, preprocessed=preprocessed, ) return resolve(symbol) ...
Python
1