text
string
label_name
string
labels
int64
} let delimiter = if quoted_object_key { LabelStyle::Quote } else { LabelStyle::None }; self.highlight_delimited_and_truncated_str( delimiter, key_ref, &truncated_view, ...
Rust
0
Z parse-only struct X { x: isize } impl<'a, T, 'b> X {} //~^ ERROR lifetime parameters must be declared prior to type parameters use std::env; #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ coins, to_binary, BankMsg, Binary, Coin, Deps, DepsMut, Env, MessageInfo, Response, St...
Rust
0
at control how input audio channels are remixed into the output audio channels.</p> #[serde(rename = "RemixSettings")] #[serde(skip_serializing_if = "Option::is_none")] pub remix_settings: Option<RemixSettings>, /// <p>Used for MS Smooth and Apple HLS outputs. Indicates the name displayed by the player ...
Rust
0
from django.urls import path from . import views urlpatterns = [ path("", view=views.index), path("notes/", view=views.create_note), path("notes/<id>/", view=views.show_note), path("notes/<id>/tasks/", view=views.create_task), path("delete_note/<id>/", view=views.delete_note), path("tasks/<id>/...
Python
1
im.configModeDVBC.value = type == "DVB-C" nim.configModeDVBT.value = type == "DVB-T" nim.configModeATSC.value = type == "ATSC" nim.multiType.value = "" nim.save() nim.configModeDVBS.addNotifier(boundFunction(combinedConfigChanged, nim, slot, slot_id), initial_call=False) nim.configModeDVBC.ad...
Python
1
flg : FunctionLinkingGraph = d3dc.create_function_linking_graph(None).unwrap(); /// let errors : TextBlob = flg.get_last_error().unwrap(); /// assert!(errors.is_empty(), "No errors were reported by flg"); /// ``` pub fn get_last_error(&self) -> Result<TextBlob, MethodError> { let mut errors = nu...
Rust
0
# Concatenate the two embeddings along the sequence dimension - (B, 77*2, 2304) text_hidden = torch.cat([text_hidden_Gemma, text_hidden_ModernBert], dim=1) del text_hidden_Gemma, text_hidden_ModernBert # Encode batch using VAE - downsample by a factor of 8 # G...
Python
1
rotobuf::Clear for SetAvatarResponse { fn clear(&mut self) { self.clear_status(); self.clear_player_data(); self.unknown_fields.clear(); } } impl ::std::cmp::PartialEq for SetAvatarResponse { fn eq(&self, other: &SetAvatarResponse) -> bool { self.status == other.status && ...
Rust
0
ePoint::D60) => { Some(Mat3::from_cols_array(&ADOBE_1998_D65_TO_AP0_D60).transpose()) } (RGBPrimaries::ADOBE_1998, WhitePoint::D65, RGBPrimaries::CIE_RGB, WhitePoint::E) => { Some(Mat3::from_cols_array(&ADOBE_1998_D65_TO_CIE_RGB_E).transpose()) } (RGBPrimaries::AD...
Rust
0
import bayesnewton import objax import numpy as np import pandas as pd import matplotlib.pyplot as plt import time y = pd.read_csv('../data/normalized_alpha_counts.csv', index_col=[0]) x = pd.read_csv('../data/alpha_time_points.csv', index_col=[0]) y = y.rename(index={'ENSMUSG00000015879': 'Fam184b', 'ENSMUSG0000005...
Python
1
 d<Xc@sdZddlZddlZddlZddlZddlZyddlmZWnek roe ZnXdddddd gZ d Z d Z d Z d ZdZyedZWnek rdZnXyedZdZWn#ek r"dZdZnXdefd...
Python
1
set_input_type(np.float32) yield ( self.create_inference_config(), generate_trt_nodes_num(attrs, True), 1e-5, ) self.trt_param.precision = paddle_infer.PrecisionType.Half program_config.set_input_type(np.float16) yield ( self.create...
Python
1
std::u64::MAX - 1 ensures that the parent check doesn't // cause addition overflow. // (Block::make_block) assumed_postcondition!(self.height < std::u64::MAX); self.height } pub fn round(&self) -> Round { // Round numbers: // - are reset to 0 periodically. ...
Rust
0
> { let writer = Writer::from(self.rkv.write()?); Ok(writer) } } /// A reference to a EnvironmentWrite #[derive(Shrinkwrap, Into)] pub struct EnvironmentWriteRef<'e>(EnvironmentReadRef<'e>); impl<'e> ReadManager<'e> for EnvironmentWriteRef<'e> { fn reader(&'e self) -> DatabaseResult<Reader<'e>...
Rust
0
choices.sort(key=operator.itemgetter(1)) return choices class JobSummaryForm(BaseJobForm): completed_count_day_limit = forms.IntegerField( label="Count completed jobs from this many days back", min_value=1, max_value=settings.JOB_MAX_DAYS, required=False, initial=3, ) ...
Python
1
std::fmt::Debug for Secret { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "[secret]") } } pub fn is_token(s: &str) -> anyhow::Result<()> { if s.starts_with("oauth:") { anyhow::bail!("token should not have `oauth:` as a prefix") } if s.len() != 30 { ...
Rust
0
ding data...", 10), ("Quality control filtering...", 25), ("Normalization and scaling...", 45), ("Principal component analysis...", 60), ("Clustering analysis...", 75), ("Differential expression...", 90), ("Generating visual...
Python
1
m = self.calculate_checksum(packet) packet.append(checksum) # 清空输入缓冲区并发送指令 self.ser.reset_input_buffer() self.ser.write(bytes(packet)) # 等待响应 time.sleep(0.02) if self.ser.in_waiting >= 8: ...
Python
1
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Core utilities. Provides the :class:`AskFor` class, which is used to prompt for a password. ''' from getpass import getpass import os def provyfile_path_from(args): if args: path = args[0] if not os.path.exists(path): raise IOError('prov...
Python
1
iasInfo>; fn add_write(name: String, i: usize, map: &mut AliasInfoMap) { map.entry(name).or_default().add_write(i); } fn add_inout(name: String, i: usize, map: &mut AliasInfoMap) { map.entry(name).or_default().add_inout(i); } fn add_use(name: String, map: &mut AliasInfoMap) { ...
Rust
0
s. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use crate::errors::Phase; pub type PhaseMap<'a, T> = arena_collections::SortedAssocList<'a, Phase, T>; <reponame>Matthias247/async_trait_experiments<gh_stars>1-10 //! Benchmarks for as...
Rust
0
# -*- coding: utf-8 -*- # JARVIS Chatbot - a simple RAG with PDF files # Create: 03 July 2024 # Author: Mr.Jack _ www.bicweb.vn # Version: 0.1.6 # Update: 28 April 2025 import openai import os from typing import Any # kept for potential future use # Set OpenAI API key from env (loaded via utils) openai.api_key = os....
Python
1
V7_UNKNOWN_FREEBSD, ARMV7_UNKNOWN_NETBSD_EABIHF, ARMV7_WRS_VXWORKS_EABIHF, ARMV7A_NONE_EABIHF, ARMV7S_APPLE_IOS, I386_APPLE_IOS, I686_APPLE_DARWIN, I686_UNKNOWN_HAIKU, I686_UNKNOWN_NETBSD, I686_UNKNOWN_OPENBSD, MIPS_UNKNOWN_LINUX_UCLIBC, ...
Rust
0
et lo = val & 0x7f; base128.push(lo as u8); val >>= 7; loop { if val == 0 { base128.reverse(); return base128; } let lo = val & 0x7f; base128.push(lo as u8 | 0x80); val >>= 7; } } #[proc_macro] pub fn encode_int(input: TokenStream) -> Toke...
Rust
0
= time.time() model.eval() model.load_state_dict(torch.load('./Wights/Best_' + args.dataset + '_Net.pkl')) tar_v, pre_v = valid_epoch(model, test_loader, criterion) OA, AA, Kappa, CA = output_metric(tar_v, pre_v) print("Final records:") print("Maxmial Accuracy: %f, inde...
Python
1
C_c:.3f}"), mo.md(f"alpha_c={alpha_c:.3f}"), mo.ui.altair_chart(chart + chart_regression + chart_points), ] ) return ( C_c, alpha_c, chart, chart_points, chart_regression, df, df_points, df_regression, flops,...
Python
1
00000000000065b2u64, 0x0000000000000000u64, 0x0000000000000000u64, 0x0000000000000000u64, 0x0000000000000000u64, 0x0000000000000000u64, ]); let z_expect = Fq2 { c0: Fq::from_repr(c0).unwrap(), c1: Fq::from_repr(c1).unwrap(), }; assert_eq!(x, &x_exp...
Rust
0
import numpy as np from tqdm import tqdm import pickle import argparse # reference: https://stackoverflow.com/questions/3067529/a-set-union-find-algorithm class DisjointSet(object): def __init__(self): self.leader = dict() # maps a member to the group's leader self.group = dict() # maps a grou...
Python
1
= (0..t).map(|i| histogram[i]).sum() / sum // omega1(t) = (t..256).map(|i| histogram[i]).sum() / sum // // mu0(t) = (0..t).map(|i| histogram[i] * i).sum() / sum / omega0(t) // mu1(t) = (t..256).map(|i| histogram[i] * i).sum() / sum / omega1(t) // // mu0(t) = mu0'(t) / omega0(t) // mu1(t) = ...
Rust
0
from django.contrib import admin from .models import AuditLog @admin.register(AuditLog) class AuditLogAdmin(admin.ModelAdmin): list_display = ('table_name', 'record_id', 'changed_by', 'action', 'change_timestamp') search_fields = ('table_name', 'record_id', 'changed_by__username') readonly_fields = ('table...
Python
1
2)] = make_matrix_elem(mat, self.ports[*t1], self.ports[*t2]); } } } fn commit(&mut self) { // Load our last guess as the new operating point self.op = self.guess.clone(); } fn load(&mut self, vars: &Variables<f64>, an: &AnalysisInfo, opts: &Options) -> Stamps<f64> { ...
Rust
0
# from playwright.async_api import async_playwright, Browser, BrowserContext ,Page from playwright.sync_api import Browser import pytest @pytest.fixture(scope='class',autouse=True) def page_spokopolish(browser: Browser): context = browser.new_context() context.set_default_timeout(10000) page = context.new_...
Python
1
# -*- coding:utf8 -*- # 爬取众筹网的信息 import requests import codecs from bs4 import BeautifulSoup from bs4 import NavigableString def read_html(url, file_handler): i = 0 html = None while i < 5: # try5次 try: html = requests.get(url) except IOError: print(IOError) ...
Python
1
e = f'resource "buildkite_pipeline" "{slug}" {{\n' resource += f' name = "{name}"\n' resource += f' repository = "{repository}"\n' resource += f' steps = {steps}\n' if description: resource += f' description = "{description}"\n' if default_branch: reso...
Python
1
int_transform, img_transform, label_transform \ in zip(self.joint_transform_list, self.img_transform_list, self.label_transform_list): if joint_transform: img_label = np.concatenate((img, label), axis=-1) img_label = joint_transform(img_label) ...
Python
1
er_path = path self.console.append(f"Loaded Master file: {path}") depth_logger.info(f"Loaded Master file: {path}") def select_secondary(self): path, _ = QFileDialog.getOpenFileName(self, 'Open Secondary JSON', '', 'JSON Files (*.json)') if path: self.secondary_pa...
Python
1
# 250136 [PCCP 기출문제] 2번 / 석유 시추 from collections import deque def solution(land): def bfs(ci, cj, idx): Q = deque([(ci, cj)]) area = 1 while Q: i, j = Q.popleft() for di, dj in dr: ni, nj = i + di, j + dj if 0<=ni<n and 0<=nj<m and ...
Python
1
value self.setGoal(value) def atTarget(self) -> bool: return self._position_pid.atGoal() def useOutput(self, output: float, setpoint: wpimath.trajectory.TrapezoidProfile.State): """Use the output from the controller object.""" self._pid_component = output self._desired_...
Python
1
信息不一致,无法合并。请检查 PTRS(B):{inconsistent_ptrs}") else: # 灌注信息一致,可以安全地去重 injection_df_unique = injection_df.drop_duplicates(subset='PTRS(B)') # 以 imaging_df 为基准,基于 PTRS(B) 列合并 merged_df = pd.merge(imaging_df, injection_df_unique, on='PTRS(B)', how='left') # 检查是否有未匹配的记录 unmatched_ptrs_b...
Python
1
#!/usr/bin/python3 """ This script defines a City class to work with MySQLAlchemy ORM. """ from model_state import Base, State from sqlalchemy import Column, Integer, String, ForeignKey class City(Base): """City class Attributes: __tablename__ (str): The table name of the class id (int): The i...
Python
1
nd pink beanie! Perfect girly fall outfit! Find details on fashion blog daily dose of charm by lauren lindmark" negative_prompt = "blurry, ugly, duplicate, poorly drawn, deformed, mosaic" base_image, upscale_image, tunningFree_image = inference.generate_image(prompt, negative_prompt=negative_prompt, seed=3407)...
Python
1
call super::hash here? for (msg, hash) in message_hashes.iter() { let test_hashes = super::hash(&msg.as_bytes()); for (i, test_hash) in test_hashes.iter().enumerate() { println!("Test {}", i); assert_eq!(hash[i], test_hash[i]); } } ...
Rust
0
` type you give to /// this constructor. You must never use this type in another arena, /// lest you might be able to mix up the indices of the two, which /// could lead to out of bounds access and thus **Undefined Behavior**! pub unsafe fn new(_: B) -> NanoArena<T, B> { Nano...
Rust
0
("bf91f3") } fn default_title_color() -> String { String::from("38bdae") } fn default_limit_works() -> usize { 10 } fn default_limit_images() -> usize { 3 } #[derive(Deserialize, PartialEq, Debug, Clone)] enum SortKey { #[serde(alias = "watcher")] WatchersCount, #[serde(alias = "satisfaction")] Satisfa...
Rust
0
} } else { let pivot = get_pivot(column_range.len()); if ident[index] == 'L' { column_range = column_range[..pivot].to_vec(); } else if ident[index] == 'R' { column_range = column_range[pivot..].to_vec(); } } ...
Rust
0
calling pause on OctoPrint.") self.OctoPrintPrinterObj.pause_print() #pyright: ignore[reportUnknownMemberType] octoprint has no typing def OnScriptHook(self, script_type: str, script_name: str) -> Optional[Tuple[Optional[List[str]], Optional[List[str]]]]: # We use OctoPrint's scripts system to dy...
Python
1
import os import numpy as np import argparse import torch def get_videos_list(root_dir): videos_list = [] for person_id in sorted(os.listdir(root_dir)): person_path = os.path.join(root_dir, person_id) # for video_id in sorted(os.listdir(person_path)): # video_path = os.path.join(per...
Python
1
code if bool_config_lvl_EI and event.key != pygame.K_ESCAPE and event.key != pygame.K_RETURN: if event.key == pygame.K_BACKSPACE: lvl_end = lvl_end[:-1] elif not event.unicode.isalpha(): lvl_end...
Python
1
et_certificate( "crt" ), # The cert file path for TLS (used if sslctx is None) # sslctx=sslctx, # The SSLContext to use for TLS (default None and auto create) keyfile=helper.get_certificate( "key" ), # The key file path for TLS (used if ...
Python
1
RUNC: _bindgen_ty_1 = 8; pub const MSG_PROXY: _bindgen_ty_1 = 16; pub const MSG_TRUNC: _bindgen_ty_1 = 32; pub const MSG_DONTWAIT: _bindgen_ty_1 = 64; pub const MSG_EOR: _bindgen_ty_1 = 128; pub const MSG_WAITALL: _bindgen_ty_1 = 256; pub const MSG_FIN: _bindgen_ty_1 = 512; pub const MSG_SYN: _bindgen_ty_1 = 1024; pub ...
Rust
0
"TEST"); } } mod test_to_snake { use paste::paste; macro_rules! m { ($id:ident) => { paste! { const DEFAULT_SNAKE: &str = stringify!([<$id:snake>]); const LOWER_SNAKE: &str = stringify!([<$id:snake:lower>]); const UPPER_SNAKE: &str = str...
Rust
0
bmax[1],box.bmax[2])) assert np.all(np.mean(box.verts,0).dot(box.A.T) < box.b) assert np.all((box.verts*(1-1e-4)).dot(box.A.T) < box.b) assert np.any((box.verts*(1+1e-4)).dot(box.A.T) > box.b) #rotated Lx = npr.random() Ly = npr.random() Lz = npr.random() print('Lx = %.2f, Ly = %.2f, Lz...
Python
1
} // Return (f32, f32, f32) rather than lab::Lab so that the example works even if // the library is built without lab feature. Normally, this would just return // lab::Lab and the library would be built with lab feature enabled (which is // the default). fn from_rgb(rgb: u32) -> (f32, f32, f32) { let lab = ...
Rust
0
ter: prefix!(atto); "acd/m²", "attocandela per square meter", "attocandelas per square meter"; @zeptocandela_per_square_meter: prefix!(zepto); "zcd/m²", "zeptocandela per square meter", "zeptocandelas per square meter"; @yoctocandela_per_square_meter: prefix!(yocto); "ycd/m²", "y...
Rust
0
ze) @staticmethod def _get_backend_denom_scaler(denom_meta: TokenMeta): scale = Decimal(f"1e{-denom_meta.decimals}") return scale @staticmethod def _floor_to(value: Decimal, target: Decimal) -> Decimal: result = int(floor(value / target)) * target return result @st...
Python
1
-> profile_pictures (profile_picture)) allow_tables_to_appear_in_same_query!( users, profile_pictures, )<reponame>Linuus/keyseebee #![no_main] #![no_std] // set the panic handler use panic_halt as _; use core::convert::Infallible; use embedded_hal::digital::v2::InputPin; use hal::gpio::{gpiob, Floating, Inp...
Rust
0
right = n1_copy.combine(n2_copy).combine(n3_copy); if left.is_nan() && right.is_nan() { true } else { approx_eq!(f64, left, right, F64Margin::default()) } } }; ($name:ident: f32) => { #[allo...
Rust
0
import aegnn.models.layer import aegnn.models.networks from aegnn.models.detection import DetectionModel from aegnn.models.recognition import RecognitionModel from aegnn.models.corner import CornerModel from aegnn.models.corner_superpoint import CornerSuperpointModel from aegnn.models.corner_heatmap import CornerHeatMa...
Python
1
self { RedisValue::Bytes(_) => true, _ => false, } } /// Check if the value is a `QUEUED` response. pub fn is_queued(&self) -> bool { match *self { RedisValue::Queued => true, _ => false, } } /// Check if the inner string value can be cast to an `f64`. pub fn is_float(&...
Rust
0
where Self: Sized, { OffsetAmp { signal: self, offset: offset, } } /// Produces an `Iterator` that scales the amplitude of the sample of each channel in every /// `Frame` yielded by `self` by the given amplitude. /// /// # Example /// /// ...
Rust
0
""" Archivo: temporizador_pyqt5.py Autor: Edwin Yoner Fecha: 20/02/2025 Descripción: Este programa crea una interfaz gráfica con PyQt5 que muestra un QLabel (etiqueta) y un QTimer (temporizador). El temporizador incrementa un contador y actualiza el texto de la etiqueta cada segundo. Requisitos: - Ten...
Python
1
in the dictionary yet name = unique_key(lnames) lnames[name] = thelist return "<%s>" % name substr = list_re.sub(listrepl, substr) # convert all lists to named templates # newnames are constructed as needed numsubs = None base_rul...
Python
1
cly.layers.as_mut_vec()[0].objects.iter_mut() .position(|obj| obj.instance_id == 0x001d015b) .unwrap(); let sunchamber_layer_change_trigger = scly.layers.as_mut_vec()[0].objects.as_mut_vec().remove(idx); *scly.layers.as_mut_vec()[1].objects.as_mut_vec() = vec![sunchamber_layer_change_trigger]; ...
Rust
0
); assert_eq!(node_to_string(tree.root, &nodes), "[[1,2],[[3,4],5]]"); assert_eq!( nodes, vec![ Node { parent: Some((8, Side::Left)), value: Pair { left: 1, right: 2 } }, Node { parent: Some((0, Left)), ...
Rust
0
w()); // if (angles[0] > Math.PI / 2) { // angles[0] -= Math.PI; // } angles[[1, 0]] = T::from(2.).unwrap().neg() * self.quat_tra().w() / norm_a; let m1 = q_b / norm_a; let m2 = *screwaxis * self.quat_rot().w() * self.quat_tra().w() / (norm_a * ...
Rust
0
# Generated from TacticNotations.g by ANTLR 4.7.2 from antlr4 import * from io import StringIO from typing import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\f") buf.write("f\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\...
Python
1
'nl': 'Guam', 'nmg': 'Guam', 'nn': 'Guam', 'no': 'Guam', 'nqo': 'ߜ߭ߎߥߊߡ', 'nyn': 'Gwamu', 'or': 'ଗୁଆମ୍', 'pa': 'ਗੁਆਮ', 'pa-Guru': 'ਗੁਆਮ', 'pcm': 'Guam', 'pl': 'Guam', 'ps': 'ګوام', 'pt': 'Guam', 'qu': 'Guam', 'rm': 'Guam', 'rn': 'Gwamu', 'ro': 'Guam', 'rof': 'Gwam', 'ru': 'Гуам', 'rwk': 'Gwam', 'saq': 'Gwam', 'sbp': 'G...
Python
1
etrics //! [Monitor][TaskMonitor] key [metrics][TaskMetrics] of tokio tasks. //! //! In the below example, a [`TaskMonitor`] is [constructed][TaskMonitor::new] and used to //! [instrument][TaskMonitor::instrument] three worker tasks; meanwhile, a fourth task //! prints [metrics][TaskMetrics] in 500ms [intervals][TaskMo...
Rust
0
d=f"WA-0-{my_opt['stage']}", player=[2, 1] if my_opt["is_group"] else [1], max_times=int(my_opt["max_times"]), global_plan_active=my_opt["global_plan_active"], deck=my_opt["deck"], battle_plan_1p=my_opt["battle_plan_1p"]...
Python
1
#Cliente TCP import sys import socket import os sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../') from dotenv import load_dotenv from threading import Thread from security.decifrarMsg import decifrarMsg from security.cifrarMsg import cifrarMsg load_dotenv() global tcp_con def receber(): glob...
Python
1
class DevConfig: def __init__(self): self.ENV = "development" self.DEBUG = True self.PORT = 5000 self.HOST = "0.0.0.0"
Python
1
for_18_or_above( fraud_check: subscription_models.BeneficiaryFraudCheck, ) -> bool: age_at_fraud_check = _get_age_at_fraud_check(fraud_check) if age_at_fraud_check is None: return False return eligibility_api.is_18_or_above_eligibility(fraud_check.eligibilityType, age_at_fraud_check) def _get_...
Python
1
exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum ThingGroupIndexingMode { Off, On, /// Unknown contains new variants that have been added since this code was generated. ...
Rust
0
[16;"1000000010001000";32], [16;"0100010000000100";32], [16;"0010001000100000";32], [16;"0000000100010001";32], [16;"0000100010001000";32], [16;"0100000001000100";32], [16;"0010001000000010";32], [16;"0001000100010000";32], //M1 [32;"100010...
Rust
0
for match in re.finditer(pattern, text): entity = TextEntity( entity_type=entity_type, value=match.group(0), normalized_value=self._normalize_entity(entity_type, match), start_pos=match.start(), ...
Python
1
APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate serde; pub use self::serde::ser::{Serialize, Serializer}; pub us...
Rust
0
import pygame import math class ShapeRenderer: @staticmethod def create_polygon_surface(points, color, width=0): # Calculate the bounding box of the polygon min_x = min([p[0] for p in points]) max_x = max([p[0] for p in points]) min_y = min([p[1] for p in points]) max_y ...
Python
1
(and quite possible) unsafe impl Sync for WinBuf {} // SEND: Maintains no external references (Vec is Send) unsafe impl Send for WinBuf {} assert_trait!(Vec<u32> : Send); impl Clone for WinBuf { fn clone(&self) -> WinBuf { WinBuf { dims: self.dims, // SAFE: &ptr means that window will not resize data: Unsa...
Rust
0
an, [song]) window.show() self._info.connect("activate", on_information) def set_rating(value): song = player.song song["~#rating"] = value app.librarian.changed([song]) self._rating_item = rating = RatingsMenuItem([], app.library) quit...
Python
1
ns `items` which is a reserved word in jinja2. This method renames that key for snap_categories. :param categories: Dict of categories :return: Dict of categories""" snap_categories = categories snap_categories["categories"] = snap_categories["items"] del snap_categories["items"] return ...
Python
1
#!/usr/bin/env python3 """ P3 — Program 5: Final Report & TeX-ish Summary Short story (header): Summarize which claims were proved, show short human sentences, and emit a tiny TeX-ish file you could paste into a note. Overview: - Reads './cases/bus/proof/normalized_claims.json' + './cases/bus/proof/proof_verdic...
Python
1
# noqa: B023 return if destw == end_offs - start_offs: for at, run in arange(start_offs, end_offs): rle_append_modify(linea, (at, run)) # noqa: B023 return # encoded version has different width o = start_offs ...
Python
1
_message, "invalid%20request%20data"); } _ => panic!("Wrong error"), } } // L1019A Pull headers empty hash #[test] pub fn pull_headers_empty_hash() { let (_server, config) = bootstrap_node(); let client = Config::attach_to_local_node(config.node_config.get_p2p_port()).client(); let err ...
Rust
0
(pos, block_id) => { let block = blocks.get_block(*block_id); if block.size.x > 1 || block.size.y > 1 { unimplemented!("Multiblock sizes not implemented!"); } let entity_builder = lazy_update .create_entity(&entiti...
Rust
0
# # Copyright © 2020-present Peter M. Stahl pemistahl@gmail.com # # 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 applicabl...
Python
1
add_reporter(reporter) metrics.add_reporter(foo_reporter) sensor = metrics.sensor('kafka.requests') sensor.add(metrics.metric_name('pack.bean1.avg', 'grp1'), Avg()) sensor.add(metrics.metric_name('pack.bean2.total', 'grp2'), Total()) sensor2 = metrics.sensor('kafka.blah') sensor2.add(metrics.met...
Python
1
ucture(creep: &Creep, target: &Structure) -> Res<ActionResult> { match creep.repair(target) { ReturnCode::Busy => Ok(ActionResult::Continue), ReturnCode::Ok | ReturnCode::NotEnough => Ok(ActionResult::Done), ReturnCode::NotInRange => { creep.move_to(target); Ok(Action...
Rust
0
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use std::collections::BTreeMap; use std::collections::Bound::{Included, Unbounded}; use...
Rust
0
); } let mut poly2 = shapeops::Polygon::new(); for points in [ //[(32., 32.), (32., 80.), (80., 32.)], // [(56., 32.), (56., 80.), (104., 32.)], //[(32., 32.), (32., 48.), (48., 48.), (48., 32.)], //[(32., 0.), (32., 64.), (64., 64.), (64., 0.)], [(0., 0.), (0., 64.)...
Rust
0
_domain_keyinput(mapper::config::KeyInput("Control-Shift-Return".to_string())).ok(), Some( mapper::KeyInput::new( mapper::Key::new(keysyms::KEYNAME_TO_KEYSYM.get("Return").unwrap().clone()), mapper::Modifiers::new( vec![ map...
Rust
0
r an area of interest in a DrawingArea pub const HOVER_OK: Condns = Condns(1 << 6); pub const HOVER_NOT_OK: Condns = Condns(1 << 7); pub const HOVER_CONDITIONS: Condns = Condns(HOVER_OK.0 | HOVER_NOT_OK.0); pub const NEXT_FLAG: u128 = 1 << 8; pub fn hover_change(hover_ok: bool) -> Change { if hover_ok { Ch...
Rust
0
} /// Returns 0.0 if `x < edge`, otherwise it returns 1.0. pub fn step_scalar<N: Number>(edge: N, x: N) -> N { if edge > x { N::zero() } else { N::one() } } /// Returns 0.0 if `x[i] < edge`, otherwise it returns 1.0. pub fn step<N: Number, D: Dimension>(edge: N, x: &TVec<N, D>) -> TVec<N, ...
Rust
0
import gradio from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, execution_queue_count, limit_resources, temp_frame, output_options, common_options, source, target, output, preview, trim_frame, face_analyser, face_selector, face_masker def pre_...
Python
1
and green fill. fn draw_rounded_rectangle(mut display: Display) -> Result<Display, std::convert::Infallible> { use embedded_graphics::{ pixelcolor::Rgb888, prelude::*, primitives::{PrimitiveStyleBuilder, Rectangle, RoundedRectangle}, }; let style = PrimitiveStyleBuilder::new() ...
Rust
0
er, // clone, iterate, etc. // An internal Vec should do, as we are unlikely to need direct access to specific entries once we // have a usage (we can do it anyway, but searching sequentially). If we needed something more // powerful we can always write conversions from Vec/HashMap to Usage. impl Usage { /// Create...
Rust
0
} } } impl MemoryMappedReadOnlyFile { pub fn new(path: &str) -> Result<Self, String> { // here we add a + 8 to map in an extra zero-filled word so that we can // do unaligned reads for bits let len = std::fs::metadata(path).map_err(|e| e.to_string())?.len() as usize; let mut c_...
Rust
0
IsExpected::True => "succeeds", IsExpected::False => "failed", } } fn passed(&self) -> bool { self == &IsExpected::True } } pub trait Runner { fn run_test_cases(&self) -> Result<()>; } struct SeqRunner { cargo_file_dir: PathBuf, check_compile: TestCases, } i...
Rust
0
aram _builtins.str first_address: The first IP address of the range. :param _builtins.str last_address: The last IP address of the range. """ pulumi.set(__self__, "first_address", first_address) pulumi.set(__self__, "last_address", last_address) @_builtins.property @pulumi.gette...
Python
1
&str) -> Result<SignedAmount, ParseAmountError> { let mut split = s.splitn(3, " "); let amt_str = split.next().unwrap(); let denom_str = split.next().ok_or(ParseAmountError::InvalidFormat)?; if split.next().is_some() { return Err(ParseAmountError::InvalidFormat); } ...
Rust
0
results.append((name,buy_date)) if len(results): print('These stocks have crossed 21 days limit. Sell them at 1:1.5 or 1:1 or at Market Price') for item in results: print(f"{item[0]} bought on {item[1]}\n") print('-'*75,'\n') def total_pl(sel...
Python
1