text
string
label_name
string
labels
int64
ient,&key); let data = messages::to_hex_string(&tx); let tx_info: TransactionResponse = self .inner .public(ApiKind::Explorer) .query(&json!({ "tx_body": data })) .post("v1/transactions") .unwrap(); assert_eq!(tx_info.tx_hash, tx.hash(...
Rust
0
untain View, CA 94042, USA. use crate::midi_event::{MIDIChannelVoiceMessage, MIDIStatus}; /// MIDI file format /// /// MIDI files have three different formats: 0, 1, and 2. Format 0 means the MIDI file /// has a single track chunk, whereas formats 1 and 2 indicate one _or more_ track chunks. /// A longer discussion ...
Rust
0
[`Score`] if _any_ [`Score`]s are at or above the configured `threshold`. ### Example ```ignore Thinker::build() .when( WinningScorer::build() .push(MyScorer) .push(MyOtherScorer), MyAction::build()); ``` */ #[derive(Debug)] pub struct WinningScorer { threshold: f32, ...
Rust
0
a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits...
Rust
0
t if t == SUPPORTED_TYPES[1].0 => SUPPORTED_TYPES[1].1.clone(), t if t == SUPPORTED_TYPES[2].0 => SUPPORTED_TYPES[2].1.clone(), t if t == SUPPORTED_TYPES[3].0 => SUPPORTED_TYPES[3].1.clone(), t if t == SUPPORTED_TYPES[4].0 => SUPPORTED_TYPES[4].1.clone(), t i...
Rust
0
= msc_utils.update_dict(config, extra_config) # skip stages skip_config = skip_config or {} for stage in [MSCStage.BASELINE, MSCStage.OPTIMIZE, MSCStage.COMPILE]: if stage not in config: continue for key in ["all", stage]: if key not in skip_config: ...
Python
1
: C) -> RTDResult<Ok> { async_caller!(Ok); async_caller(&self.api, transfer_chat_ownership.as_ref()).await } pub async fn unpin_all_chat_messages<C: AsRef<UnpinAllChatMessages>>(&self, unpin_all_chat_messages: C) -> RTDResult<Ok> { async_caller!(Ok); async_caller(&self.api, unpin_all_chat_messages....
Rust
0
ignature": "3045022100B342C7159E1AD7FAA13452C1FB01F77A107263AFB06E93F9B4F307EF9DF9F98E0220690C964D89146250E879B9EA5ED311C3317631F1F6450360603E6818AFFB5FAF", "date": 611552870, "hash": "AB2A25557FF03911A8FC0A412293BE9D9FCB20CDD530EE05957A9859F8467C32", "inLedger": 12839308...
Rust
0
fn drop(&mut self) { print!("Drop!"); } } <gh_stars>1-10 //! Watchdog peripherals use crate::{ hal::watchdog::{Watchdog, WatchdogEnable}, pac::{DBG, FWDGT}, time::MilliSeconds, }; /// Wraps the Free Watchdog Timer (FWDGT) peripheral pub struct FreeWatchdog { fwdgt: FWDGT, } const IRC40K_K...
Rust
0
import sys, pathlib, sqlite3 parent_dir = str(pathlib.Path(__file__).parent.parent.resolve()) sys.path.append(parent_dir) # データベース接続 def connect_db(): return sqlite3.connect('attendance.db') # DBへの書き込み def writeSQL(query: str = None): if query == None: return conn = connect_db() cursor = con...
Python
1
import tkinter as tk from geometry.vector3 import Vector3 from geometry.triangle import Triangle from engine.mesh_builder import generate_points, build_triangles_from_grid from typing import Callable, Tuple def project_point(v: Vector3, scale=100, offset_x=400, offset_y=300) -> tuple: return (v.x * scale + offset...
Python
1
class Vahicle: def __init__(self, model, brand, origin_by): self.model = model self.brand = brand self.origin_by = origin_by class Bike(Vahicle): pass class Car(Vahicle): pass class Bus(Vahicle): pass #Bike.............................................
Python
1
_jni_bindgen! { /// public interface [OnAccountsUpdateListener](https://developer.android.com/reference/android/accounts/OnAccountsUpdateListener.html) /// /// Required feature: android-accounts-OnAccountsUpdateListener public interface OnAccountsUpdateListener ("android/accounts/OnAccountsUpdateListene...
Rust
0
import os import re import matplotlib.pyplot as plt def extract_retransmissions(file_path): """ Extract the number of retransmissions from an iperf3 output file. """ with open(file_path, 'r') as file: content = file.read() # Find the line that contains the retransmissions in the summary...
Python
1
!(ret.is_ok()); /// let fd = ret.unwrap(); /// let mut buf = [0_u8; 4 * 1024]; /// let ret = nc::read(fd, buf.as_mut_ptr() as usize, buf.len()); /// assert!(ret.is_ok()); /// let n_read = ret.unwrap(); /// assert!(n_read <= buf.len() as nc::ssize_t); /// assert!(nc::close(fd).is_ok()); /// ``` pub fn read(fd: i32, buf_...
Rust
0
import json import os from os.path import join as opj from tqdm import tqdm import sys import torchaudio downsample_rate = 16000 clean_train_path = '/home/lz/SEpycode/DATASET/VB_Demand/clean_trainset_28spk_wav' noisy_train_path = '/home/lz/SEpycode/DATASET/VB_Demand/noisy_trainset_28spk_wav' clean_test_path = '/hom...
Python
1
import os from pathlib import Path USER_HOME = Path.home() SEARCH_FOLDERS = [ USER_HOME / "Desktop", USER_HOME / "Documents", USER_HOME / "Downloads", USER_HOME / "Music", USER_HOME / "Pictures", USER_HOME / "OneDrive", #only if onedrive is available on the machine.. ] word_to_number = { ...
Python
1
_instr(ld3))] #[stable(feature = "neon_intrinsics", since = "1.59.0")] pub unsafe fn vld3q_p64(a: *const p64) -> poly64x2x3_t { transmute(vld3q_s64(transmute(a))) } /// Load multiple 3-element structures to three registers #[inline] #[target_feature(enable = "neon")] #[cfg_attr(test, assert_instr(nop))] #[stable(f...
Rust
0
,unit=1) AU = ContractType_6_12('au','SHFE',multiplier=15,unit=0.05) BU = ContractType_6_12('bu','SHFE',multiplier=10,unit=2) RU = ContractType_5_9_1('ru','SHFE',multiplier=10,unit=5) XH = ContractType_5_9_1('XH','SHFE',multiplier=10,unit=5) #测试用 #大连 M = ContractType_5_9_1('m','DCE',multiplier=10,unit=1) A = Contrac...
Python
1
"""CLI entry point for cli-mcpx.""" import sys from collections.abc import Callable from functools import partial from typing import Annotated import typer from cli_mcpx import __version__ def create_version_message(version: str) -> str: """ Create version message string. Pure function that formats th...
Python
1
cls = [self.cls_token_id] if token_ids_1 is None: return len(cls + token_ids_0 + sep) * [0] return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0] @property def vocab_size(self): return len(self.sp_model) def get_vocab(self): vocab = {self.conv...
Python
1
100); arena.retain(|_index, &mut i| i % 2 == 1); assert!(arena.items().all(|data| data % 2 == 1)); assert_eq!(arena.len(), 50); } #[test] fn entry_bind() { let mut arena = Arena::<i32>::from_iter(0..100); // simulate `drain_filter::<Vec<_>>()` let mut drain = Vec::new(); for entry in arena...
Rust
0
() { os.write_string(2, &v)?; } if let Some(ref v) = self.path.as_ref() { os.write_string(3, &v)?; } if let Some(ref v) = self.base_name.as_ref() { os.write_string(4, &v)?; } if let Some(v) = self.success { os.write_bool(5, ...
Rust
0
def main(): text_path = "books/frankenstein.txt" text = get_text(text_path) word_count = count_words(text) character_count = count_characters(text) make_report(text_path, word_count, character_count) def get_text(path): with open(path) as f: return f.read() def count_words(text): w...
Python
1
} impl Debug for CellConfig<'_> { fn fmt(&self, f: &mut Formatter) -> Result { f.debug_struct("CellConfig") .field("size", &self.size()) .field("cpu_set", &self.cpu_set()) .field("mem_regions", &self.mem_regions()) .field("cache_regions", &self.cache_regions...
Rust
0
, ), // Making sure our pattern-matching is exhaustive _ => Circle::new( (coordinates[0], coordinates[1]), 3, ShapeStyle::from(&BLACK).filled(), ), }; root_area .draw(&point) .expect(...
Rust
0
_base_ = './retinanet_r50_fpn_2x_coco.py' model = dict( pretrained='open-mmlab://resnext101_32x4d', backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN',...
Python
1
import httpx_auth import httpx_auth._oauth2.implicit def test_corresponding_oauth2_implicit_flow_instance(monkeypatch): monkeypatch.setattr( httpx_auth._oauth2.implicit.uuid, "uuid4", lambda *args: "27ddfeed4e-854b-4361-8e7a-eab371c9bc91", ) okta = httpx_auth.OktaImplicit( ...
Python
1
h2" else mock_service ) mock_service.tasks.return_value = mock_tasks mock_tasks.delete.return_value = mock_delete mock_delete.execute.return_value = None # Google API returns None on successful deletion mock_userinfo_service.userinfo.return_value.get.return_value.exe...
Python
1
def count_ngrams(tokens, n): """Returns a dictionary mapping tuples of n-grams with order n to the number of times that n-gram occurred in list tokens.""" ngrams = dict() if len(tokens) < n: return ngrams for i in range(len(tokens) - n + 1): ngram = tuple(tokens[i:i+n]) if ngram not in ngrams: ngrams[ngr...
Python
1
s_unions' global up3gpint3sm import ktnlkrd95ua, xdb1et86mbn, g5t3r9ss12s as oprcupe9hyt, m5dn9ho_4ek, z3ldi4cl1h6 as rt_zxquzjva, ot9hm0y214f as rmk1rv1v0nw, fuvcpqtb280 @(mpj_i4tvb8d, b'') def iavsacbshj2(wgba6rh35vc=0j, votyv_s47y6: evclawxe6_j=b'', jd69euo6n0y=0.0, dueqqqv1u9d=0, rnsbgzrw_a7: qmdntyql77l=Fa...
Python
1
91\xc7$\x9dWt\x9f\xb8\ \xf7\xf49\x89\xe0\x97I\xf8C\xe2\xc9t\xcb\xeb\xfb\x0b\ \xbb\xef\x87\xba\x0e\xa6o\xed.L\x17\xb0^\xeb\x90\xe9\ \xb3\xea\x0d\x1d\xc4j\xad=\xa1\x91\xe4\xfb\x1e\x93\xa8\x0b\ \xdd\x1bMY\x194\xed>\xd5Da9\x9f\x0b\x88\xfc\ M\xa8\xf8&\xda\xfa$\xb7\xba\xbe\x87V\xd2o\xb5\x8d\ 8\xc9g\xab\x5c\xd9\xbc\xb3\xd9\xd...
Python
1
from typing import Any, Mapping, TypedDict import numpy as np from faster_whisper.audio import decode_audio # type: ignore SUPPORTED_MODELS = ["tiny", "tiny.en", "small", "small.en", "base", "base.en", "medium", "medium.en", "large-v2", "large-v3"] WordData = TypedDict( "WordData", {"word": str, "start": float ...
Python
1
data.rs"); // TODO: Find a way to automatically register types? // This would avoid having to specify all types in each build.rs file. generate_pyi_file( "../ssbh_data_py/ssbh_data_py/matl_data.pyi", &["def read_matl(path: str) -> MatlData: ..."], &[ MatlData::pyi(), ...
Rust
0
")] pub private_metadata: Option<String>, #[serde(with = "serde_with::rust::string_empty_as_none")] pub callback_id: Option<SlackCallbackId>, #[serde(with = "serde_with::rust::string_empty_as_none")] pub external_id: Option<String>, } #[skip_serializing_none] #[derive(Debug, PartialEq, Clone, Seria...
Rust
0
), (0xfa30, &['\u{4FAE}']), (0x9cb, &['\u{09C7}', '\u{09BE}']), (0x2f858, &['\u{58AC}']), (0x1f5b, &['\u{03A5}', '\u{0314}', '\u{0300}']), (0x6c2, &['\u{06C1}', '\u{0654}']), (0x2f950, &['\u{78CC}']), (0xb5c, &['\u{0B21}', '\u{0B3C}']), (0xfa4d, &['\u{7949}']), (0x1f93, &['\u{03B7}',...
Rust
0
= 16 mean = 0.1307 std = 0.3081 num_cls = 10 target_transform = None def get_dataset(name, rootdir, dset, image_size, num_channels, download=True): is_train = (dset == 'train') print('get dataset:', name, rootdir, dset) params = data_params[name] transform = get_transform(params, image_size, num_channels) ta...
Python
1
> c, None => return None, }; let secp = static_secp_instance(); let secp = secp.lock(); let mut calc_slate = Slate::blank(2, false); calc_slate.fee = slate.fee; for d in slate.sigs.iter() { calc_slate.participant_data.push(ParticipantData { public_blind_excess: d.xs, public_nonce: d.nonce, part_sig: ...
Rust
0
road: Railroad = INPUT_STR.parse().unwrap(); assert_eq!(*EXPECTED, railroad); } #[test] fn run_test() { let mut railroad: Railroad = EXPECTED.clone(); let (last_train_loc, first_crash_loc) = railroad.run_until_last().unwrap(); assert_eq!(Some((3, 7)), first_crash_loc); ...
Rust
0
let z1_int = to_big_int!(z.p.1); // now we have the following: // z + w * p = x * y // which is // z0 + w0p0 - x0y0 (0) // + 2^m *( z1 + w0p1 + w1p0 - x0y1 - x1y0 ) (1) // + 2^2m *( w1p1 - x1y1 ) (2) ...
Rust
0
erm::lterm::aspect_map::*; pub use term::lterm::aspect_pid::*; pub use term::lterm::aspect_port::*; pub use term::lterm::aspect_reference::*; pub use term::lterm::aspect_smallint::*; pub use term::lterm::aspect_tuple::*; pub use term::lterm::lterm_impl::*; <gh_stars>10-100 use crate::platform::UserData; use bevy::{ ...
Rust
0
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv(r"/Users/anmolchadgal/Downloads/Airquality.csv") print(df.head()) print(df.info()) print(df.shape) #missing values print("\nMissing values in each column:") print(df.isnull().sum()) #Summary statistics pri...
Python
1
(0x32A7, 'M', '左'), (0x32A8, 'M', '右'), (0x32A9, 'M', '医'), (0x32AA, 'M', '宗'), (0x32AB, 'M', '学'), (0x32AC, 'M', '監'), (0x32AD, 'M', '企'), (0x32AE, 'M', '資'), (0x32AF, 'M', '協'), (0x32B0, 'M', '夜'), (0x32B1, 'M', '36'), (0x32B2, 'M', '37'), (0x32B3, 'M', '38'), (0...
Python
1
urces specification and metadata", mf.name) } } bd.totals.base = sum; bd.totals.extra = extra; Ok(bd) } /// Resource use for a single region pub fn resources(conf: &Config, region: &Region) -> Result<()> { let bd = resources_region(&conf, region)?.normalise(); println!("{}", serde_json...
Rust
0
ds contributions /// * Treasury cuts #[derive(Debug, Clone, Eq, PartialEq)] pub struct Parameters { /// This is an initial_value for the linear or halvening function. /// In the case of the linear function it is the value that is going to be calculated /// from the contribution. pub initial_value: u64, ...
Rust
0
sult, Process}; use std::cmp; use std::collections::HashMap; use std::time::Duration; pub struct ReadBytes { header: String, unit: String, fmt_contents: HashMap<i32, String>, raw_contents: HashMap<i32, u64>, max_width: usize, } impl ReadBytes { pub fn new() -> Self { let header = Strin...
Rust
0
from django.contrib import admin from django.urls import path, include from webapp import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('webapp.urls')) ]
Python
1
use their idx to /// double-check whether no other functions were added to the module in the meantime). #[must_use] pub fn finish(self) -> Vec<Hook> { let mut result: Vec<_> = self.map.into_inner().into_iter().map(|(_k, v)| v).collect(); result.sort_by_key(|hook| hook.idx); result ...
Rust
0
fill_input_buffer .expect("non-null function pointer"), ) .expect("non-null function pointer")(cinfo) == 0 { return 0 as libc::c_int; } next_input_byte = (*datasrc).next_input_...
Rust
0
} pdf_set_string( instring, wbuf.as_mut_ptr(), (4096i32 as u64).wrapping_sub(obufleft), ); 0i32 } unsafe extern "C" fn maybe_reencode_utf8(mut instring: *mut pdf_obj) -> i32 { let mut inbuf: *mut u8 = 0 as *mut u8; let mut inlen: i32 = 0; let mut non_ascii: i32 = 0i3...
Rust
0
; } haystack.find(needle).map_or(-1, |pos| pos as sys::mrb_int) } // MRB_API mrb_int mrb_str_strlen(mrb_state *mrb, struct RString *s) // // NOTE: Implemented in C in `mruby-sys/src/mruby-sys/ext.c`. // MRB_API void mrb_str_modify_keep_ascii(mrb_state *mrb, struct RString *s) // // MRB_API void mrb_str_modify...
Rust
0
fn map_address(&self, address: u32) -> &[u8]; fn map_address_mut(&mut self, address: u32) -> &mut [u8]; fn read_word(&self, address: u32) -> u32; fn read_halfword(&self, address: u32) -> u16; fn read_byte(&self, address: u32) -> u8; fn write(&self, address: u32, value: &[u8]); } <reponame>bradu...
Rust
0
_from_ranges() { assert_eq!(ByteRange::from(1..10), ByteRange::from(1..=9)); assert_eq!(ByteRange::from(..10), ByteRange::from(..=9)); } #[test] fn test_range_bounds() { assert_eq!(ByteRange::from(0..10).start_bound(), Bound::Included(&0)); assert_eq!(ByteRange::from(..10).s...
Rust
0
import sys input = sys.stdin.readline # https://www.acmicpc.net/problem/17413 # 1. 알파벳 소문자('a'-'z'), 숫자('0'-'9'), 공백(' '), 특수 문자('<', '>')로만 이루어져 있다. # 2. 문자열의 시작과 끝은 공백이 아니다. # 3. '<'와 '>'가 문자열에 있는 경우 번갈아가면서 등장하며, '<'이 먼저 등장한다. 또, 두 문자의 개수는 같다. # 태그는 '<'로 시작해서 '>'로 끝나는 길이가 3 이상인 부분 문자열 # '<'와 '>' 사이에는 알파벳 소문자와 공백만 ...
Python
1
ary /// extern crate rand; // Link rand library /// /// use num::traits::FromPrimitive; // Allow overloading of from_i64() /// use num::bigint::BigUint; // Add support for large unsigned integers /// /// use rand::rngs::OsRng; // Import the os's rng /// /// use ed25519_dalek::Keypair; //...
Rust
0
ently running in a jupyter notebook. Used for automatic selection. Returns ------- style: Optional[Union['pygments.style.Style',str]] If pygments is installed, the style object or string, suitable for use as the "style" argument to pygments formatters. If pygments is not i...
Python
1
u8 { let mut count = 0; for delta_row in [self.height - 1, 0, 1].iter().cloned() { for delta_col in [self.width - 1, 0, 1].iter().cloned() { if delta_row == 0 && delta_col == 0 { continue; } let neighbor_row = (row + delta_...
Rust
0
let dy = y - 500.0; let r = f64::sqrt(dx * dx + dy * dy) / 4.0; let a = f64::atan2(dy, dx); // *buf = calc_rgb(f64::sin(r/10.0)/2.0+0.5*f64::cos(a*10.0)/2.0+0.5, f64::sin(r/13.0)/2.0+0.5*f64::cos(a*17.0)/2.0+0.5, 0.5); *buf = calc_rgb((r % 50.0) / 50.0,...
Rust
0
ine(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Secure mask for pin P0_1\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PIO0_PIN1_SEC_MASK_A { #[doc = "0: Pin state is block...
Rust
0
_socket_file_path(socket_file_path.as_ref())?; Self::unix_domain_socket_data_from_socket_file_path(socket_file_path) } &Abstract { ref abstract_name } => Self::unix_domain_socket_data_from_abstract_name(&abstract_name[..]), }; self.bind(&local_address, length) } #[inline(always)] fn unix_domain_sock...
Rust
0
# Atividade 06: # Soma de Números Pares: # Escreva um programa que use um laço for para somar # todos os números pares de 1 a 50 e exiba o resultado final. r = 0 n = 0 for n in range(5): r = n + n print(r + n) print(r)
Python
1
" ) plt.savefig(f"kmeans_scaled_{chrom}.png") # plt.savefig(f"dbscan_scaled_{chrom}.png") plt.figure(1) plt.clf() (min_y, max_y) = reduced_data[:, 0].min(), reduced_data[:, 0].max() # scatter PC1/coordinate color by cluster plt.scatter(y=reduced_data[:, 0], x=coords, marker=".", s=2, c=labels, cmap="Set1") # plot kno...
Python
1
?; let conn = db::connect(&spec)?; match args.map(|a| a.value_of("NAME")).flatten() { Some(to) => rollback_to(conn, to), None => rollback_latest(conn), } } fn rollback_to(mut conn: Connection, to: &str) -> Result<()> { let ms = get_migrations()?; let to_migration = match ms.get_mig...
Rust
0
pub fn new(inner: R) -> Self { Self { inner, offset: 0, line_buf: Vec::new(), } } /// Consumes a single sequence line. /// /// If successful, this returns the number of bytes read from the stream (i.e., the line width) /// and the number of ba...
Rust
0
the application for changes to take effect." ) toggle_btn.click( fn=toggle_extension, outputs=[gr.HTML()], ).then( fn=lambda button_text: gr.Button( "Enab...
Python
1
""" This is a simplified URLs list that omits any of the multiplayer features, assuming that all badges will be managed from the admin interface, and most badges will be awarded in badges.py """ from django.conf.urls import patterns, include, url from django.conf import settings from .feeds import (AwardsRecentFeed, ...
Python
1
"group":"output", "comment":"*_his.nc History file in NetCDF format"}) # self.dict.append({"name":"hisinterval", "keyword":"HisInterval", "type":"float", "default":600.0, "group":"output", "comment":"Interval (in s) between history outputs"}) # self.dict.append({"...
Python
1
rResult; /// Gets the GUID of the preferred VR audio device. /// /// **out** `deviceOutGuid` The GUID of the user's preferred VR audio device to use, which will be valid upon a successful return value, else it will be NULL. /// /// Returns an `ovrResult` indicating success or failure. In the case ...
Rust
0
ta modes/types. The parsers seem to assume a single // data type and since we start with an ASCII `MATRIX` header the rest of // the data gets treated as a string as well. // // We make sure that there isn't an ECI bit set and we just push the bytes, // this seems to help since the decoder doesn't a...
Rust
0
ized_end=2051 _globals['_GETSERVICEROLLOUTREQUEST']._serialized_start=2053 _globals['_GETSERVICEROLLOUTREQUEST']._serialized_end=2133 _globals['_ENABLESERVICEREQUEST']._serialized_start=2135 _globals['_ENABLESERVICEREQUEST']._serialized_end=2212 _globals['_ENABLESERVICERESPONSE']._serialized_start=2214 _glo...
Python
1
_42 = object.key("GroupBy").start_object(); crate::json_ser::serialize_structure_crate_model_dimension_group(&mut object_42, var_41)?; object_42.finish(); } if let Some(var_43) = &input.filter { let mut object_44 = object.key("Filter").start_object(); for (key_45, value_46) in va...
Rust
0
y monitor webapp", ) class Worker(BaseModel): loglevel: str = Field(..., description="Worker loglevel") terminal_args: list[str] = Field( ..., min_items=0, description="Pre-command args. Use to invoke the command through another shell/terminal.", ) celery_args: list[str] = ...
Python
1
start(&mut self, data: StateData<'_, GameData<'_, '_>>) { let StateData { world, .. } = data; // Crates new progress counter self.progress_counter = Some(Default::default()); let mut physics_world: PhysicsWorld<f32> = PhysicsWorld::new(); physics_world.set_gravity(Vector2::new(0...
Rust
0
user profile summary for each cluster profile_path = "analysis_set3/trial2_graph_based/plots_clustering/user_cluster_profiles_PCA_KMeans.txt" with open(profile_path, "w") as f: for cluster, row in centroids_df.iterrows(): f.write(f"\nCluster {cluster} profile (PCA+KMeans):\n") # Show top 3 root cate...
Python
1
ep mode. ManualTemperature = 0b01, /// Measure the voltage once and then transition to sleep mode. ManualVoltage = 0b10, /// Measure temperature and voltage at regular 1 second intervals. Automatic = 0b11, } /// Specifies a configurable alarm from the chip. #[derive(Copy, Clone, IntoEnumIterator)] ...
Rust
0
or import a ship previously exported via Space Ark Constructor. Setting your ship Name and Class will dictate Total Available Mass to spend on Ship Design. Reference the italicized text below the various Ship Design steps to see calculated statistics like Critical T...
Python
1
._container.exec_run(cmd) assert exit_code == 0 return res.decode("utf-8") def get_env(self, key: str) -> str: """Return env var value from docker container""" res: str = self.exec(f"bash -c 'echo \"${key}\"'") return res.rstrip(" \n") def copy_to(self, host_file_path: ...
Python
1
sing provided redirect_uri %s', request.redirect_uri) if not is_absolute_uri(request.redirect_uri): raise errors.InvalidRedirectURIError(request=request) # The authorization server MUST verify that the redirection URI # to which it will redirect the access token matc...
Python
1
"`*"] #[cfg(feature = "Win32_Foundation")] pub fn SearchTreeForFileW(rootpath: ::windows_sys::core::PCWSTR, inputpathname: ::windows_sys::core::PCWSTR, outputpathbuffer: ::windows_sys::core::PWSTR) -> super::super::super::Foundation::BOOL; #[doc = "*Required features: `\"Win32_System_Diagnostics_Debug\"`*"]...
Rust
0
5_scalar_t>())).limb as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(ristretto255_scalar_t), "::", stringify!(limb) ) ); } extern "C" { pub static mut ristretto255_scalar_one: ristretto255_scalar_t; pub static ...
Rust
0
import pytest @pytest.mark.parametrize( 'middleware_request', ({'FAKEUSERAGENT_FALLBACK': 'firefox'},), indirect=True ) def test_random_ua_set(middleware_request): assert 'User-Agent' in middleware_request.headers @pytest.mark.parametrize( 'middleware_request', ({'FAKEUSERAGENT_FALLBACK': 'f...
Python
1
#[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `INTERRUPT_CORE0_CPU_INT_CLEAR`"] pub type INTERRUPT_CORE0_CPU_INT_CLEAR_R = crate::R<u32, u32>; #[doc = "Write proxy for field `INTERRUPT_CORE0_CPU_INT_CLEAR`"] pub struct INTERRUPT_CORE0_CPU_INT_CLEAR_W<'a> { w: &'a ...
Rust
0
eturns the socket address of the local half of this connection. /// /// # Examples /// /// ```no_run /// use std::os::unix::net::UnixStream; /// /// fn main() -> std::io::Result<()> { /// let socket = UnixStream::connect("/tmp/sock")?; /// let addr = socket.local_addr().expec...
Rust
0
# Copyright (c) OpenMMLab. All rights reserved. from logging import Logger from typing import Sequence from unittest import TestCase import torch from torch import Tensor, nn from torch.utils.data import DataLoader, Dataset from mmrazor.engine.runner.utils import CalibrateBNMixin class ToyModel(nn.Module): def...
Python
1
value)?; Ok(()) } } extern crate clap; use prettytable::{Table}; use std::env; use crate::api::models; use crate::api::requests; use clap::App; use clap::load_yaml; pub async fn parse_arguments() { let yaml = load_yaml!("clicommands.yml"); let matches = App::from_yaml(yaml).get_matches(); if...
Rust
0
ub struct Field(Array2<Option<Tile>>); impl Field { pub fn new(width: usize, height: usize) -> Self { Self(Array2::default((height, width))) } pub fn from_array(array: Array2<u32>) -> Self { let (h, w) = (array.shape()[0], array.shape()[1]); let mut field = Self::new(w, h); ...
Rust
0
t = 10_000u64; init_reward_manager( &mut context, &reward_manager, &token_account, &mint.pubkey(), &manager_account.pubkey(), 3, ) .await; let key: [u8; 32] = rng.gen(); let oracle_priv_key = SecretKey::parse(&key).unwrap(); let secp_oracle_pubk...
Rust
0
eturn { "type": "object", "properties": {key: value_to_schema(value[key]) for key in value}, } # if it is none, return null elif value is None: return {"type": "object", "nullable": True} def is_uuid(key): return isinstance(key, str) and is_valid_uuid(key) def is_...
Python
1
te:") self._print_grid(node.grid) new_nodes = [] # Find first empty cell empty_cells = [] for i in range(2): for j in range(2): if node.grid[i][j] == 0: empty_cells.append((i, j)) if not empty_cells: ...
Python
1
ut.push_str(format!("[{}", a[(i, 0)]).as_str()); for j in 1..PRINT_ELEMENTS_LIMIT { expected_output.push_str(format!(", {}", a[(i, j)]).as_str()); } expected_output.push_str("],\n "); } expected_output.push_str("...,\n "); for i in PRINT_ELEMEN...
Rust
0
_F * s0) * 0.007 * comp, (fz + SECTOR_SIZE_F * s2) * 0.007 * comp]) * general_h; let middle = SECTOR_SIZE_F / 2.; let highest = (middle + height * 40.).max(0.).min(SECTOR_SIZE_F) as usize; ...
Rust
0
#!/usr/bin/env python # coding=utf-8 ''' Created on 2016年8月3日 @author: guoqi ''' import sys import argparse from Crypto.Cipher import AES from binascii import b2a_hex, a2b_hex ### CRYPT CRYPT_MODE_BASE = "base" # TODO, not read enrcypt strint format CRYPT_MODE_AES = "aes" CRYPT_KEY = 'PM28fwczoEqj3emr' CRYPT_PADD...
Python
1
import numpy as np import pytest import pandas as pd from pandas.core.arrays.integer import ( Int8Dtype, Int16Dtype, Int32Dtype, Int64Dtype, UInt8Dtype, UInt16Dtype, UInt32Dtype, UInt64Dtype, ) @pytest.fixture( params=[ Int8Dtype, Int16Dtype, Int32Dtype, ...
Python
1
ator: HumanAddr::from("addr0000"), fee_address: None, repay_address: None, }) .unwrap(), ), }); let res = handle(&mut deps, env, msg).unwrap(); assert_eq!( res.messages, vec![ CosmosMsg::Wasm(WasmMsg::Execute { ...
Rust
0
import pandas as pd import re def convert_week_to_days(week_str): """ 将孕周字符串转换为总天数,支持两种格式: 1. "11w+6" 表示11周加6天 2. "13w" 表示13周(即13周加0天) 1周 = 7天 """ if pd.isna(week_str): # 处理空值 return None # 先尝试匹配"Xw+Y"格式 match = re.match(r'(\d+)w\+(\d+)', str(week_str)) if match: ...
Python
1
import tkinter def add(*args): """Wczyta dowolnie duzo wart jako tuple""" print(args) def xd(**kwargs): """Wczyta dowolnie duzo wart jako tuple""" print(kwargs) xd(a=1, b=2, c=3) window = tkinter.Tk() window.title("Janek to grubas") window.minsize(500, 500) my_label = tkinter.Label(window, text=...
Python
1
S implementation pub use::tokio_rustls::rustls::*; pub use tokio_rustls::webpki; pub use webpki_roots; pub mod connector; pub use connector::{HttpsOnlyConnector, HttpsConnector}; #![feature(plugin)] #![plugin(interpolate_idents)] #[macro_use] extern crate apache2; #[macro_use] mod code; use apache2::{Request, Stat...
Rust
0
# Crie um programa em Python que simule um sistema de login. O programa deve permitir ao usuário três tentativas para acertar o nome de usuário e a senha corretos. Caso o usuário erre as credenciais, o programa deve fornecer uma mensagem informando quantas tentativas restam. Se o usuário acertar, uma mensagem de boas-...
Python
1
ejercicos # dado la siguiente lista de nombres desordenados: # [juan,ana, carlos, elena, pedro] # utiliza el algoritmo de burbuja para ordenalos alfabeticamente """ nombres = ["juan","ana","carlos","elena","pedro"] print("la lista de los nombres antes ordenar: ", nombres) # algoritmo de la burbuja n = len(nombre...
Python
1
return super(New_Module, self).save(*args, **kwargs) if self.boat.exists() != self.text_block.exists() != self.past_trips.exists() != self.trips_today.exists(): raise ValidationError('Не больше одного выбора в ManyToManyField') if not (self.boat.exists() or self.text_block.exists(...
Python
1