text
string
label_name
string
labels
int64
(); vertices.sort_unstable_by_key(|w| w.index); RawMesh { vertices: vertices.into_iter().map(|w| w.vertex).collect(), triangles: self .indices .chunks_exact(3) .map(|i| TriangleDefinition([i[0], i[1], i[2]])) .collec...
Rust
0
default_value("1.1.1.1"), ) .arg(Arg::with_name("domain-name").required(true)) .get_matches(); let domain_name_raw = app.value_of("domain-name").unwrap(); let dns_server_raw = app.value_of("dns-server").unwrap(); let mut request_as_bytes: Vec<u8> = Vec::with_capacity(512); let m...
Rust
0
import torch from typing import List, Tuple, Dict, Optional from enum import Enum from collections import namedtuple from .samd_config import SamdConfig from .sam import DynSAM, StaticSAM from profile_utils import profile_decorator from transformers import LlamaConfig, LlamaForCausalLM # from transformers import Llam...
Python
1
if idx == 0: # 过期的棒棒糖 if 10.17 <= amount < 101.7: # 10.17-101.7, 积分清零 points = 0 bonus_report += '很不幸,你获得了【过期的棒棒糖】,本次获取的积分清零T_T' elif amount >= 101.7: # 多于101.7,积分减半 points = int(points // 2) bonus_report += '很不幸,你获得了【过期的棒棒糖】,本次获取的积分减半T_T' elif idx...
Python
1
(|f| &f.ident) .flatten(); let a = fields.next(); let b = fields.next(); let c = fields.next(); let name = &input.ident; TokenStream::from(quote! { impl ops::Add<#name> for #name { type Output = #name; fn add(self, other: #name) -> #name { #name...
Rust
0
ize, Deserialize)] pub struct NpcMoves { pub npc_moves_remaining: usize, pub ticks_till_next_npc_move: usize, // Essentially, whether "response" systems should run pub move_was_made: bool, } impl NpcMoves { pub fn player_can_move(&self) -> bool { self.npc_moves_remaining == 0 && self.ticks_...
Rust
0
ependencies. The # condition we impose is that there is a git submodule for every dependency in # the workspace, but not necessarily conversely. E.g. Bloaty is a dependency # not used by any of the targets built by Bazel. if len(workspace_git_hashes - git_submodule_hashes) > 0: print( "Found discrepancies b...
Python
1
let b = Matrix::randsn(m, nrhs); let x = solve_driver(&a, &b).expect("solve failed unexpectedly"); assert_eq!(x.dims(), (n, nrhs)); println!("a*x\n{}\nb\n{}", &a * &x, &b); assert_fpvec_eq!(&a * &x, &b); } #[test] fn test_solve_approx_nrhs_narrow() { let (m,...
Rust
0
# λ Calculus 當中的所有資料結構都是用 closure 達成的 # 換言之,所有的資料結構都是函數閉包。 # Church Booleans : Logic IF = λ c:λ x:λ y:c(x)(y) # if: λ c x y. c x y # if c then x else y. TRUE = λ x:λ y:x # if true then x # 兩個參數執行第一個 FALSE = λ x:λ y:y # if false then y # 兩個參數執行第二個 AND = λ p:λ q:p(q)(p) # if p then q else p OR = λ p:λ q:p(p)(q)...
Python
1
_usage(&program, &opts); process::exit(1); } }; // Default to "stream" if traffic type is not defined. let traffic_type = matches.opt_str("t"); if let Some(t) = traffic_type { match t.as_ref() { "stream" => {} "datagram" => { warn!("da...
Rust
0
lf) -> bool { self.status() == ItemStatus::Init as u8 } // reset只会把状态从shutdown变更为init // 必须在shutdown之后调用 pub(crate) fn reset(&self) { //self.status_cas(ItemStatus::Shutdown as u8, ItemStatus::Init as u8); self.status.store(Init as u8, Ordering::Release); self.try_wake(); ...
Rust
0
, 'shi': 'ⵜⴰⵟⴰⵍⵢⴰⵏⵜ', 'shi-Latn': 'Taṭalyant', 'shi-Tfng': 'ⵜⴰⵟⴰⵍⵢⴰⵏⵜ', 'si': 'ඉතාලි', 'sk': 'taliančina', 'sl': 'italijanščina', 'smn': 'italiakielâ', 'sn': 'chiTariana', 'so': 'Talyaani', 'sq': 'italisht', 'sr': 'италијански', 'sr-Cyrl': 'италијански', 'sr-Latn': 'italijanski', 'su': 'Italia', 'su-Latn': 'Italia', 's...
Python
1
= df / d(\sigma_t-1(()) #### strategy 1 #### # xyz_difference = self.get_finite_difference_of_density(fr + 1, nex_density_index.x, nex_density_index.y, nex_density_index.z) # cur_def_grad = -1. * self.density_tot_frames.grad[fr, i, j, k] * xyz_difference...
Python
1
} <reponame>erikhyrkas/doglang use crate::lex::group::Group; #[derive(PartialEq, Eq, Debug)] pub enum MatchRepeats { Once, ZeroOrMore, OneOrMore, ZeroOrOne, } pub fn min_matches(match_repeats: &MatchRepeats) -> i32 { let result; match match_repeats { MatchRepeats::Once => { result = 1...
Rust
0
_uchar_U(*(rs_allocation*)buf3692, *(uint32_t*)buf3693, *(uint32_t*)buf3694); *(uchar*)buf3695 = rsGetElementAtYuv_uchar_V(*(rs_allocation*)buf3696, *(uint32_t*)buf3697, *(uint32_t*)buf3698); *(uchar*)buf3699 = rsGetElementAtYuv_uchar_Y(*(rs_allocation*)buf3700, *(uint32_t*)buf3701, *(uint32_t*)buf3702); *(...
Rust
0
: last_test = not last_test char_lines = line_for_char[ch] if len(char_lines) >= expect_size: continue elif length < 5 and char_lines and len(lines[char_lines[0]]) > 10: continue line_for_char[ch].append(k) used_line...
Python
1
n = int(input()) for i in range(n) : n1,n2,n3 = map(float,input().split(" ")) media = (n1*2 + n2 *3 + n3*5)/10 print("%.1f"%media)
Python
1
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Odoo 17 Accounting', 'version': '2.0.2', 'category': 'Accounting', 'summary': 'Accounting Reports, Asset Management and Budget, Recurring Payments, ' 'Lock Dates, Fiscal Year, Accounting Dashboard, Fina...
Python
1
# Import standard python modules import logging # Import python types from typing import Optional, Dict # Import device utilities from device.utilities.logger import Logger # Import i2c package elements from device.utilities.communication.i2c.exceptions import MuxError class MuxSimulator(object): """I2C mux si...
Python
1
new(); sql.push_str("INSERT INTO art (id, title, votes) VALUES "); for i in 0..bs { if i != 0 { sql.push_str(", "); } sql.push_str(&format!("({}, 'Article #{}', 0)", aid, aid)); aid +=...
Rust
0
ocess; fn load_patterns() -> Result<day21::PatternSet, failure::Error> { let stdin = io::stdin(); let mut patterns = day21::PatternSet::new(); for line in stdin.lock().lines() { patterns.insert(&line?)?; } Ok(patterns) } fn main() { let patterns = match load_patterns() { Ok(p) => p, Err(e) => ...
Rust
0
ART_UTX_END_INT_UMSK: i32 = -2; pub const UART_URX_END_INT_POS: u32 = 1; pub const UART_URX_END_INT_LEN: u32 = 1; pub const UART_URX_END_INT_MSK: u32 = 2; pub const UART_URX_END_INT_UMSK: i32 = -3; pub const UART_UTX_FIFO_INT_POS: u32 = 2; pub const UART_UTX_FIFO_INT_LEN: u32 = 1; pub const ...
Rust
0
e setup fig = plt.figure( figsize=( width, width / (len(labels) if fixed_height is None else fixed_height) + 0.1, ) ) grid = AxesGrid( fig, 111, nrows_ncols=(1, len(labels)), cbar_mode="edge", cbar_size="10%" ) for ax in grid: ax.axes.xaxis.set...
Python
1
import time import turtle from ball import Ball from brick_manager import BrickManager from colors_fonts import BG_COLOR from paddle import Paddle from scoreboard import Scoreboard screen = turtle.Screen() screen.bgcolor(BG_COLOR) screen.setup(width=1000, height=600) screen.title("Breakout") screen.tracer(0) paddle ...
Python
1
lob.glob(self.norm('aa*') + os.sep) self.assertEqual(len(res), 2) # either of these results is reasonable self.assertIn(set(res), [ {self.norm('aaa'), self.norm('aab')}, {self.norm('aaa') + os.sep, self.norm('aab') + os.sep}, ]) ...
Python
1
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QPushButton, QLabel from PyQt6.QtGui import QFont from PyQt6.QtCore import QProcess import os class RadiationMapTab(QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): layout = QVBoxLayout() label ...
Python
1
f.ball.y = self.screen_height // 2 self.ball.vx = self.ball.speed * direction self.ball.vy = self.ball.speed * random.choice([-1, 1]) * random.uniform(0.5, 1.0) def draw_scores(self): left_text = self.font.render(str(self.left_score), True, self.ball.color) right_text = self.font....
Python
1
.SSKJr SSKrSSKrSSKrSSKrSSKrSSKJr SSK J r SSK J r SSK JrJr SSKJr SSKJr SS KJrJr SS KJr SS KJrJrJrJrJrJrJ r J!r!J"r" SS K#J$r$J%r% SS K&J'r'J(r(J)r)J*r* \RV"SSSS9r,...
Python
1
v[0]; iv[..n - 1].clone_from_slice(&iv_copy[1..]); iv[n - 1] = t; } } self.iv = iv; } } impl<C, P> IvState<C, P> for Cfb8<C, P> where C: BlockCipher + BlockEncrypt + NewBlockCipher, P: Padding, { fn iv_state(&self) -> GenericArray<u8, Self::Iv...
Rust
0
def availability(self, request, pk=None): """ Проверка доступности транспортного средства. """ vehicle = self.get_object() start_time = request.query_params.get('start_time') end_time = request.query_params.get('end_time') if not start_time or not end_time: ...
Python
1
"target/**", # These are not vendored from the crate - we exclude them to avoid busting caches # when we change how we generate BUILD files and such. "BUILD.bazel", "WORKSPACE.bazel", "WORKSPACE", ]), tags = [ "cargo-raze", "manual", ], version = ...
Rust
0
.push(p.parse()?); } let mut items = Vec::new(); let mut item_attributes = p.parse()?; let mut item_visibility = p.parse()?; let mut path = p.parse::<Option<ast::Path>>()?; while path.is_some() || ast::Item::peek_as_item(p.peeker(), path.as_ref()) { let ite...
Rust
0
o [aA&@sddlmZddlZddlZddlZddlZddlZddlZddlZddl m Z gdZ ej dkp@e edo@e edo@e ejd ZGd d d ejZejZd8d d Zej dkr~e gd7Z ddlZd9ddddZddZddZddZGdddeZn#e gd7Z ddlZej dkZddZdd ...
Python
1
s use anyhow::Error; use std::fs; use crate::cmd::Cmd; use crate::context::Context; use structopt::StructOpt; use std::str::FromStr; /// Clean target directory command. #[derive(StructOpt, Debug)] #[structopt(setting(structopt::clap::AppSettings::ColoredHelp))] pub struct Clean { #[structopt(about = "Type of clean...
Rust
0
dec class Parent { parent(){} } expect(typeof Parent.prototype.parent).toBe("function"); expect(typeof Parent.prototype.child).toBe("function"); "# ); // legacy_regression_10264 test!( syntax(true), |_| chain!( typescript::strip(), decorators(decorators::Config { legacy: true }) ), ...
Rust
0
#!/usr/bin/env python import argparse import json import os import sys import requests # URL for downloading OMAmer datasets OMAMER_DATASETS_URL = "https://omabrowser.org/All/{dataset}" # List of OMAmer data sets with versions OMAMER_DATASETS = { "Primates_v2.0.0": "Primates-v2.0.0.h5", "Viridiplantae_v2.0....
Python
1
import streamlit as st from matplotlib.figure import Figure from py_wanderer import ALGORITHMS, HEURISTICS from py_wanderer.plotter import plot_maze_with_paths from utils import generate_maze, solve_maze, MazeConfig def configure_page() -> None: st.set_page_config(page_title="Maze and Pathfinding Visualizer", la...
Python
1
import numpy as np DEFAULT_UPDATE_MODAL = {'img': False, 'lidar': True, 'target': True, 'action_mask': False} class StateNorm(): def __init__(self, observation_shape:dict, update_modal:dict=DEFAULT_UPDATE_MODAL) -> None: self.observation_shape = observation_shape self.update_modal = update_moda...
Python
1
epdims=keepdims) ndarray_ret = nd_reduce_func(mx.nd.array(dat), axis=axes, keepdims=keepdims) if type(ndarray_ret) is mx.ndarray.NDArray: ndarray_ret = ndarray_ret.asnumpy() assert (ndarray_ret.shape == numpy_ret.shape) or \ (ndarray_ret.shape == (...
Python
1
import random import pandas as pd data = pd.read_json('static/tarot-images.json', orient='records') cards = pd.json_normalize(data['cards']) cards['img_file'] = cards.apply(lambda row: row['img'][0] + str(row['img'][1:]), axis=1) def draw_cards(): selected_cards = cards.sample(3) return selected_cards
Python
1
ne(handle_gc,x+w,y,x+w,y+vlen) #bottom left if self.hover_zone==3: drawable.draw_line(hhandle_gc,x,y+h,x+hlen,y+h) drawable.draw_line(hhandle_gc,x,y+h,x,y+h-vlen) else: drawable.draw_line(handle_gc,x,y+h,x+hlen,y+h) drawable.draw_line(handle_gc,x,...
Python
1
arg2 in labels: raise SyntaxError('Ambiguous label {0!r}'.format( code.co_names[oparg2] )) labels[oparg2] = (offset1, offset4, tuple(block_stack)) ...
Python
1
] #[derive(Debug, Copy, Clone)] pub struct pcre2_real_code_8 { _unused: [u8; 0], } pub type pcre2_code_8 = pcre2_real_code_8; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct pcre2_real_match_data_8 { _unused: [u8; 0], } pub type pcre2_match_data_8 = pcre2_real_match_data_8; #[repr(C)] #[derive(Debug, Copy, ...
Rust
0
8_from_rsa_sk_bytes(sk: Vec<u8>) -> Results<Rsa<Public>> { match load_sk(sk) { Ok(sk) => generate_pk_rsa_pkcs8_from_rsa_sk(sk), Err(err) => Err(Errs::strs("load_sk_pkey", err)), } } /// 生成RSA公钥 fn generate_pk_rsa_pkcs1_from_rsa_sk_file<P: AsRef<Path>>( filepath: P, ) -> Results<Rsa<Public>>...
Rust
0
; execute_riscu_examples(&TEST_FILES, &solver); } #[test] #[cfg(feature = "boolector")] fn execute_riscu_with_boolector_solver() { use monster::solver::Boolector; let solver = Boolector::default(); execute_riscu_examples(&TEST_FILES, &solver); } #[test] #[cfg(feature = "z3")] fn execute_riscu_with_z...
Rust
0
2) as f32, 100.0); // shadow/stroke graphics::set_color(ctx, graphics::Color::new(0.0, 0.0, 0.0, 0.8))?; graphics::draw(ctx, &self.title_shadow, title_dest, 0.0)?; // main text graphics::set_color(ctx, graphics::Color::new(1.0, 1.0, 1.0, 1.0))?; graphics::draw(ctx, &sel...
Rust
0
u8) -> Self { match value { 0 => DisplayPosition::Degree, 1 => DisplayPosition::DegreeMinute, 2 => DisplayPosition::DegreeMinuteSecond, 3 => DisplayPosition::AustrianGrid, 4 => DisplayPosition::BritishGrid, 5 => DisplayPosition::DutchGrid,...
Rust
0
# Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', # determine if the input string is valid. # An input string is valid if: # Open brackets must be closed by the same type of brackets. # Open brackets must be closed in the correct order. # Every close bracket has a corresponding open bra...
Python
1
() { let markdown = r#" 1. First ordered list item 2. Another item 1. Actual numbers don't matter, just that it's a number 1. Ordered sub-list 4. And another item. "#; let expected = r#" First ordered list item Another item Actual numbers don't matter, just that it's a number Ordered sub-list And an...
Rust
0
salt: b"salt1234".to_vec(), hash: b"12345678901234567890123456789012".to_vec(), }; let actual = decode_string(encoded).unwrap(); assert_eq!(actual, expected); } #[test] fn decode_string_without_version_returns_correct_result() { let encoded = "$argon...
Rust
0
except Exception as e: logger.error(f"記錄決策失敗: {e}") def _update_performance_metrics(self, decision: Decision, portfolio_state: PortfolioState): """更新性能指標""" try: self.performance_metrics['total_decisions'] += 1 # 這裡需要實現更詳細的性能計算邏輯 ...
Python
1
as *mut usize, &mut msg_flags_recvd as *mut i32, raw_flags, ); assert!(status == sgx_status_t::SGX_SUCCESS); // TODO: what if retval < 0 but buffers are modified by the // untrusted OCall? We reset the potentially tampered buffers. ...
Rust
0
import requests import flet as ft import subprocess import minecraft_launcher_lib as mclib from time import sleep from flet import Theme from modules import db from random import choice from os import path, replace from . import var minecraft_directory = mclib.utils.get_minecraft_directory() runtime_version = "java-...
Python
1
here with your business transactions analysis! Based on the transaction data from [analyzed period], I've analyzed [number] transactions totaling KES [amount]: 📊 Performance Summary: - Total transactions: [number] generating KES [amount] in revenue - [Key insight about overall performance] - [Notable trend or signif...
Python
1
alue_tag = Some(serde::de::MapAccess::next_value(&mut map)?), Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; }, } } Ok(NamedTagEventList { conditions: value_conditions, ...
Rust
0
.SAX2DOM() sax2dom.startDocument() sax2dom.startElement("doc", {}) sax2dom.characters("text") sax2dom.startElement("subelm", {}) sax2dom.characters("text") sax2dom.endElement("subelm") sax2dom.characters("text") sax2dom.endElement("doc") sax2dom.endDocument() doc = sax2dom.docum...
Python
1
# Copyright 2023 The Google Earth Engine Community Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
Python
1
set([4, 5, 6]) disjoint = set_a.isdisjoint(set_b) print("5.4 Exercise 4 - Are sets disjoint?:", disjoint) # %% 6. Notes for Further Learning # - Frozen sets are immutable and hashable, ideal for dictionary keys or set elements (e.g., ML model metadata, fixed configurations). # - Use regular sets for mutable operations...
Python
1
const SYSTEM_VERSION_SRV_NAME: &str = "/system/version"; const SYSTEM_CHAIN_SRV_NAME: &str = "/system/chain_name"; const SYSTEM_PROPERTIES_SRV_NAME: &str = "/system/properties"; const SYSTEM_HEALTH_SRV_NAME: &str = "/system/health"; const PUBLISH_DELAY: Duration = Duration::from_secs(1); const SEND_MESSAGE_ERROR: &s...
Rust
0
: &GpuCommandEncoder, source: &GpuBuffer, source_offset: f64, destination: &GpuBuffer, destination_offset: u32, size: u32, ); #[cfg(web_sys_unstable_apis)] #[cfg(feature = "GpuBuffer")] # [wasm_bindgen (method , structural , js_class = "GPUCommandEncoder" , js_nam...
Rust
0
return Err(input_err(format!( "Node '{}' has no client address", node_alias ))) } }; let bls_key: Option<BlsVerKey> = match txn.txn.data.data.blskey { Some(ref blskey) => { ...
Rust
0
words=self.get_keywords(), facets=self.get_facets_config() ) # 调用 LLM response = await self.llm_engine.call(prompt) # 解析 JSON 响应 result = self._parse_llm_response(response) if result and result.get("coverage", {}).get("hit"): ...
Python
1
return await xxnx.edit( "**Silahkan Tambahkan Var** `HEROKU_APP_NAME` **untuk menambahkan blacklist**", ) blgc = f"{BLACKLIST_GCAST} {message.chat.id}" blacklistgrup = ( blgc.replace("{", "") .replace("}", "") .replace(",", "") .replace("[", "") ....
Python
1
learning(self): topics = [ "Lionel_Messi", "Football", "Sport", "FIFA_World_Cup", "Olympics", "Athletics", "Basketball", "Tennis", "Serena_Williams", "Rafael_Nadal", "Physics", "Newton's_laws_of_motion", "Gravity", "Albert_Einstein", "Relativity", "Quantum_mechani...
Python
1
try: inverno = 0 d = 0 soma = 0 while inverno < 90: temp = float(input("Digite a temperatura em graus Celsius: ")) if(temp < -15 and temp > 5): print("Temperatura fora do intervalo de inverno.") else: inverno += 1 d += 1 soma += tem...
Python
1
: DataObject, T: DataObject, { pub fn new(many_table: &'static str) -> Self { ManyFieldExpr { many_table, phantomo: PhantomData, phantomt: PhantomData, } } pub fn contains(&self, q: BoolExpr) -> BoolExpr { //let many_tbl = format!("{}_{}_Many",...
Rust
0
color='fullName', color_discrete_sequence=f1db_utils.custom_colors, markers=True, template=f1db_utils.template, labels=labels_dict, color_discrete_map = { "Scuderia Ferrari": f1db_utils.F1_RED, ...
Python
1
model_dir = 'aiqm2_dft_model' model_files = [f'cv{ii}.pt' for ii in range(8)] mlatom_model_dir, to_download = self.check_model_path(model_dir, model_files) if to_download: self.download(download_links, mlatom_model_dir) model_paths = [os.path.join(mlatom_model_dir, ...
Python
1
der_size, 0) // scale bbox[2] = (bbox[2] - border_size) // scale bbox[3] = (bbox[3] - border_size) // scale # Keep bboxes with sufficiently high scores score = bbox[4] if score > self.detection_threshold: det_bboxes.append(list(bbox)) ...
Python
1
else { Err(exceptions::PyValueError::new_err( "Schema builder object isn't valid anymore.", )) } } } impl SchemaBuilder { fn build_int_option( stored: bool, indexed: bool, fast: Option<&str>, ) -> PyResult<schema::NumericOptions> { ...
Rust
0
se_examples else example.SerializeToString()) if len(examples) >= num_examples: break return examples filenames = filepath_to_filepath_list(path) compression_types = [ tf.io.TFRecordCompressionType.NONE, tf.io.TFRecordCompressionType.GZIP, tf.io.TFRecordCompressionType.ZLIB, ]...
Python
1
] | upload Some([_sets, v]) if v.starts_with("origin.") => { *act = "upload".into(); authz_req.object.value.truncate(2); } // ["sets", "ms" <> _] | * | [CLASS_TYPE, CLASS_ID] | download ...
Rust
0
_some()); } fn get_root(&mut self) -> &mut Self::Root { self } } fn compute_path(ns: &[String], this: &str) -> String { if this.chars().any(|a| a == '/') { panic!("'/' is not allowed in names"); } let mut name = String::new(); let mut needs_separation = false; for ns ...
Rust
0
; let mut safeurl = safeurl_from(files_container_xor)?; safeurl.set_path("/testdata/subfolder/subexists.md"); let subfile_cat = safe_cmd_stdout(["cat", &safeurl.to_string()], Some(0))?; let contents = std::fs::read_to_string(format!("{}/subexists.md", TEST_FOLDER_SUBFOLDER))?; assert_eq!(subfile_ca...
Rust
0
ap(); let res = Response::new(req.hash.clone()); let route = self.get(&req.route); if let Some(route) = route { let res = route(req, res); let json = serde_json::to_string(&res).unwrap(); webview .eval(&format!("external.backend.handle({})...
Rust
0
alue*SATS_DENOMINATOR/fiat_value } } pub fn from_sats_value(fiat_unit: FiatUnit, sats_value: f64, fiat_value: f64) -> Rate{ Rate { timestamp: timestamp, fiat_unit: fiat_unit, source: SourceExchange::Custom, btc: fiat_value/( sats_value/SATS_DENOMINATOR ), sats: sats_value/fiat_...
Rust
0
::G, 0x06 => events::VirtualKeyCode::Z, 0x07 => events::VirtualKeyCode::X, 0x08 => events::VirtualKeyCode::C, 0x09 => events::VirtualKeyCode::V, //0x0a => World 1, 0x0b => events::VirtualKeyCode::B, 0x0c => events::VirtualKeyCode::Q, 0x0d => events::Virtua...
Rust
0
ut!(pipe); struct DoNothingNotify; impl Notify for DoNothingNotify { fn wake(&self) {} } let context = Context::from_notify(Arc::new(DoNothingNotify)); match pipe.poll(&context) { Poll::Event(Event::Complete(10)) => {} x => panic!("invalid output: {:?}", x), } } use s...
Rust
0
1 if attempts < self._max_tries: time.sleep(wait_secs) else: raise do_backoff(value) class HTTPType(NetworkType): """Validation type for an HTTP resource""" @staticmethod def _test_connection(url): "...
Python
1
# Code automatically generated from OptiMUS # Problem type: MIP # Problem description ''' An international goods exporter uses ships and planes to transport goods. Each ship can carry ShipCapacity containers and consumes ShipFuel liters of fuel per trip. Each plane can carry PlaneCapacity containers and consum...
Python
1
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import math from stopes.utils.tts_preprocessing.numbers.ben_Beng.words import numeric_words, units def input_sanitizer...
Python
1
// set the core to which this interrupt will be sent vector_table.msi_vector[i].msg_lower_addr.write((lower_addr & !MSIX_ADDRESS_BITS) | MSIX_INTERRUPT_REGION | (core_id << MSIX_DEST_ID_SHIFT)); //allocate an interrupt to msix vector vector_table.msi_vector[i]...
Rust
0
le PETSC_ARCH not found!"), String::from("lib"), ] .iter() .collect(); println!("cargo:rustc-link-search={}", petsc_lib_dir.display()); println!("cargo:rustc-link-lib=petsc"); let slepc_lib_dir: PathBuf = [ env::var("SLEPC_DIR").expect("Environment variable SLEPC_DIR not found!...
Rust
0
n!("hdr_sv: '{}'", hdr_sv); let hdr_v = reqwest::header::HeaderValue::from_str(&hdr_sv).unwrap(); req = req.header(hdr, hdr_v); let mut resp = req.send()?; match resp.status() { reqwest::StatusCode::NOT_FOUND => return Ok(None), _ => return Ok(Some(resp.text()?)), } } pub fn list_m...
Rust
0
en(iterable), eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time))) i += 1 end = time.time() total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) prin...
Python
1
import time import threading from pynput.keyboard import Controller, Key def is_dead(img, button_loc): #Uses the green color of the retry buttons to find the death state x, height = button_loc pixel = img[height][x] return pixel[1] > 160 and pixel[0] < pixel[1] and pixel[2] < pixel[1] def is_dead_pro...
Python
1
_ => assert!(false) } } }<gh_stars>0 use bevy::prelude::*; use bevy_egui::{egui, EguiContext, EguiPlugin}; use bevy_egui_debug::{EguiDebug, EguiDebugDerive}; #[derive(Debug, PartialEq, EguiDebugDerive)] enum ToolType { Hoe, WateringCan, None } #[derive(Debug, EguiDebugDerive)] struct SomeDat...
Rust
0
0x0d, 0x00} DEFINE_GUID! {GUID_PROCESSOR_THROTTLE_POLICY, 0x57027304, 0x4af6, 0x4104, 0x92, 0x60, 0xe3, 0xd9, 0x52, 0x48, 0xfc, 0x36} pub const PERFSTATE_POLICY_CHANGE_IDEAL: DWORD = 0; pub const PERFSTATE_POLICY_CHANGE_SINGLE: DWORD = 1; pub const PERFSTATE_POLICY_CHANGE_ROCKET: DWORD = 2; pub const PERFSTATE_POLICY_C...
Rust
0
.name == self.name.to_lowercase() // TODO: memoize } } #[derive(Clone, Default)] struct CavePath<'a> { caves: Vec<&'a Cave>, visits: HashMap<&'a String, usize>, } impl<'a> CavePath<'a> { fn new() -> Self { Default::default() } fn add(&mut self, cave: &'a Cave) { if let Some(vi...
Rust
0
RR t(MSG_KEY_RESULT_GET_FILTER_ADAPTER_FILTERRR(t MSG_KEY_RESULT_GET_FILTER_FILTERR*tMSG_KEY_RESULT_GET_FILTER(RR,RR-((stype_Result.pyR.ws  icCsoddl}|jt|jjj|}|jjj|}|jt|j d<...
Python
1
# SPDX-License-Identifier: MIT # MIT License # # Copyright (c) 2024 Kevin L. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # t...
Python
1
buffers: &Arc<PacketBuffers>) { packet_buffers .received::<AnimationServerbound>() .for_each(|(player, packet)| { let animation = match packet.hand { Hand::Main => ClientboundAnimation::SwingMainArm, Hand::Off => ClientboundAnimation::SwingOffhand, ...
Rust
0
is not None: line = '\t'.join( map(str, (item.node_id, item.node_name, item.node_type, ','.join(map(str, item.node_attr)) ))) + '\n' else: line = '\t'.join(map(str, (item.node_id, item.node_name, item.node_type))) + '\n' ...
Python
1
) .map(|piece| piece.scope.record.duration_ns) .max() .unwrap(); ui.monospace(format!("max: {:6.3} ms", to_ms(max_duration_ns))); } } fn paint_thread_info(info: &Info, thread: &ThreadInfo, pos: Pos2) { let galley = info .ctx .fonts() .lay...
Rust
0
tor.connection.alias, to_model): from_model = from_state.apps.get_model(app_label, self.model_name) schema_editor.alter_field( from_model, from_model._meta.get_field(self.new_name), to_model._meta.get_field(self.old_name), ) def de...
Python
1
) def sum_logs(key): import torch result = sum(log.get(key, 0) for log in logging_outputs) if torch.is_tensor(result): result = result.cpu() return result def compute_acc(meters): score = meters["_score_sum"].sum / meters["_sc...
Python
1
1, 2, 3, 4, 5, 6]; let mut tree = RBTree::new(); for (k, v) in keys.iter().copied().zip(vals.iter().copied()) { tree.insert(k, v); } for (k, v) in keys.iter().copied().zip(vals.iter().copied()) { assert_eq!(tree.get(&k).map(|r| *r), Some(v)) ...
Rust
0
pub fn wxTopLevelWindow_SetRepresentedFilename(self_: *mut c_void, filename: *const c_void); pub fn wxTopLevelWindow_ShowWithoutActivating(self_: *mut c_void); pub fn wxTopLevelWindow_EnableFullScreenView(self_: *mut c_void, enable: bool) -> bool; pub fn wxTopLevelWindow_ShowFullScreen(self_: *mut c_voi...
Rust
0
true) .truncate(true) .open(file_path) .expect("file"); write!(file, "{}", res).map_err(FileError::IO)?; Ok(()) } Err(rubyfmt::RichFormatError::SyntaxError) => Err(FileError::SyntaxError), Err(e) => { // we're in...
Rust
0
let s = Sys::new(); let toml = s.to_toml().unwrap(); let ip = toml.lookup("ip").unwrap().as_str().unwrap(); let re = Regex::new(r"\d+\.\d+\.\d+\.\d+").unwrap(); assert!(re.is_match(&ip)); } } mod hab { use super::super::Hab; use VER...
Rust
0