text
string
label_name
string
labels
int64
generate_plane_model(buffer, distance_threshold) ) // get the best plane-model from all iterations (highest ranking) .max_by(|(x, _y), (a, _b)| x.ranking.cmp(&a.ranking)) .unwrap() } /// Ransac Line Segmentation in parallel. /// Returns the line with the highest rating/most ...
Rust
0
import torch import torch.nn as nn import pdb CLIPMIN = 1e-4 def round_ste(x: torch.Tensor): """ Implement Straight-Through Estimator for rounding operation. """ return (x.round() - x).detach() + x def clamp_ste(x: torch.Tensor, min, max): return (x.clamp(min,max) - x).detach() + x def clamp_...
Python
1
from modules.model.ChromaModel import ChromaModel from modules.modelLoader.BaseModelLoader import BaseModelLoader from modules.modelLoader.chroma.ChromaEmbeddingLoader import ChromaEmbeddingLoader from modules.modelLoader.chroma.ChromaLoRALoader import ChromaLoRALoader from modules.modelLoader.chroma.ChromaModelLoader ...
Python
1
BIT_A { #[doc = "0: Override the default values for NRF_1Mbit mode."] OVERRIDE = 0, #[doc = "1: Do not override the default values for NRF_1Mbit mode."] NOTOVERRIDE = 1, } impl From<NRF_1MBIT_A> for bool { #[inline(always)] fn from(variant: NRF_1MBIT_A) -> Self { variant as u8 != 0 }...
Rust
0
import pybullet as p from scipy.spatial.transform import Rotation as R import math from pb_ompl import PbOMPLRobot class MyPlanarRobot(PbOMPLRobot): def __init__(self, id) -> None: self.id = id self.num_dim = 7 self.joint_idx=[0,1,2,3] self.reset() self.joint_bounds = [] ...
Python
1
def calc_deceleration_rate(initial_velocity, final_velocity, time): """ Calculates the deceleration rate given the initial and final velocities, and time period. Parameters: initial_velocity (float): The starting velocity in units per time (e.g., meters per second). final_velocity (float): The endi...
Python
1
""" Control-related nodes: PINN Estimator, Voice Control, Advanced Control """
Python
1
character_data.behavior.start_event_draw_text = now_event_draw.text climax_draw = settlement_pleasant_sensation(character_id) player_data: game_type.Character = cache.character_data[0] if (not character_id) or (player_data.target_character_id == character_id): if now_event_draw.text != "": ...
Python
1
from __future__ import annotations from mteb.abstasks.AbsTaskBitextMining import AbsTaskBitextMining from mteb.abstasks.TaskMetadata import TaskMetadata class NorwegianCourtsBitextMining(AbsTaskBitextMining): metadata = TaskMetadata( name="NorwegianCourtsBitextMining", dataset={ "path...
Python
1
pairs = [[1, 1],[2, 2],[3, 3],[4, 4]] same_count = 0 for x,y in pairs: if x == y: same_count = same_count + 1 print(same_count) #python中for循环可以遍历数组,或者是range整数 #for name in range #name如果有两个变量,那么会直接遍历到数组中的数组 range[-2, 2] # Length: ending value - starting value # 元素的顺序:序号 + 起始值 list(range(-2, 2)) # >>> [-2,...
Python
1
r m in middlewares { match m.capability_post_invoke(cur_resp) { Ok(ir) => cur_resp = ir.clone(), Err(e) => { error!("Capability middleware post-invoke failure: {}", e); return Err(e); } } } Ok(cur_resp) } /// Executes a chain o...
Rust
0
) { self.pc = addr; } pub fn dump(&self, bus: &Bus) { use op_code::OP_NAMES; print!("{:04X} ", self.pc); let mut pc = self.pc; let op = bus.inspect(pc) as usize; let name = OP_NAMES[op]; pc += 1; match ADDR_MODES[op] { AddrMode::IM...
Rust
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Python
1
link_metadata() { Ok(v) => v, Err(err) => { errors.push(err); continue; } }; if meta.is_dir() { directories.push(path); continue; } log::error!("Deleting: {:?}", &path); match remove_fil...
Rust
0
! { { let branchtracker = #branchtracker; let output = #output; let deps = #deps; tokio::spawn(async move { Self::#next_task_name(branchtracker, output, deps).await; }); } } } fn convert_vec_string_to_vec_task_name(nodes: &...
Rust
0
, _ => panic!("Invalid digit: {}", ch), } } } // impl Digit { // pub(crate) fn from_char(ch: char) -> Digit { // } // } pub(crate) fn digit(i: &str, ptr: Pointer) -> Result<(&str, Pointer, Digit), ParseError> { let (i, ptr) = whitespace(i, ptr); if let Some(ch) = i.chars().next()...
Rust
0
const RED: Color = Color { code: 'c', name: "red" }; pub const LIGHT_PURPLE: Color = Color { code: 'd', name: "light_purple" }; pub const YELLOW: Color = Color { code: 'e', name: "yellow" }; pub const WHITE: Color = Color { code: 'f', name: "white" }; pub const OBFUSCATED: Color = Color { code: '...
Rust
0
s shape (N, 4 * num_classes). Note N = num_anchors * W * H when rois is a grid of anchors. Offset encoding follows [1]_. means (Sequence[float]): Denormalizing means for delta coordinates stds (Sequence[float]): Denormalizing standard deviation for delta coordinates max_s...
Python
1
se): @classmethod def _fixture_setup(cls): super()._fixture_setup() cls.plan_1 = TestPlanFactory() cls.plan_2 = TestPlanFactory(parent=cls.plan_1) cls.plan_3 = TestPlanFactory(parent=cls.plan_1) cls.plan_4 = TestPlanFactory(parent=cls.plan_2) def test_tree_returns_d...
Python
1
"INTEL486_A_ONLY", "INTEL386_486_ONLY", "IA64", "X64", "ADX", "AES", "AVX", "AVX2", "AVX512_4FMAPS", "AVX512_4VNNIW", "AVX512_BF16", "AVX512_BITALG", "AVX512_IFMA", "AVX512_VBMI", "AVX512_VBMI2", "AVX512_VNNI", "AVX512_VP2INTERSECT", "AVX512_VPOPCNTDQ", "AVX512BW", "AVX512CD", "AVX512DQ", "AVX512E...
Rust
0
let private_key: Vec<u8> = vec![ 40, 185, 109, 70, 134, 119, 123, 37, 190, 254, 232, 186, 106, 48, 213, 63, 133, 223, 167, 126, 159, 43, 178, 4, 190, 217, 52, 66, 92, 63, 69, 84, ]; let public_key: Vec<u8> = vec![ 212, 151, 158, 35, 16, 178, 19, 27, 83, 109, 212, 138, 141, 134, 122, 246, 1...
Rust
0
pred1 + pred2, dim=1) ) loss_D2, reg2 = self.D2.calc_dis_loss( self.D2, input_fake = F.softmax(pred_target2, dim=1), input_real = F.softmax(0.5*pred1 + pred2, dim=1) ) loss = loss_D1 + loss_D2 if self.fp16: with amp.scale_loss(loss, [self.dis1_opt, self.dis2_opt]...
Python
1
t: sigma_ol[:, j] = sol[N-L+1+(m+p)*L:N-L+1+(m+2*p)*L] u_init_store[:, j-nu] = u_init.flatten() y_init_store[:, j-nu] = y_init.flatten() # Simulate closed loop for k in range(j, min(j + M, T - 1)): u_cl[:, k] = u_ol[m*n + (k - j) * m : m*n + m + (k - j) * m, j] # Up...
Python
1
ng the arguments cliswitch = module.params['pn_cliswitch'] state = module.params['state'] netmask = module.params['pn_netmask'] ospf_area = module.params['pn_ospf_area'] network = module.params['pn_network'] vrouter_name = module.params['pn_vrouter_name'] command = state_map[state] # B...
Python
1
# Copyright (c) 2024 Microsoft Corporation. # Licensed under the MIT License """Persona, entity type, relationships and domain generation prompts module.""" from .community_reporter_role import GENERATE_COMMUNITY_REPORTER_ROLE_PROMPT from .domain import GENERATE_DOMAIN_PROMPT from .entity_relationship import ( EN...
Python
1
driver, time) this_locator = self.get_locators(locator) element = self._wait.until(ec.frame_to_be_available_and_switch_to_it(this_locator)) return element def wait_invisibility(self, locator:dict, time=10): ''' Espera o elemento não estar presente na tela, altura e larg...
Python
1
, config::AdcConfig}; use rand_chacha::{ ChaCha8Rng, rand_core::SeedableRng, }; mod patterns; #[entry] fn main() -> ! { rtt_init_print!(); if let (Some(dp), Some(cp)) = ( stm32::Peripherals::take(), cortex_m::peripheral::Peripherals::take(), ) { let rcc = dp.RCC.constrain...
Rust
0
from typing import List # time: O(n^2) # space: O(1) class Solution: def rotate(self, matrix: List[List[int]]) -> None: n = len(matrix) # transpose (flip across diagonal) for row in range(n): for col in range(row + 1, n): matrix[row][col], matrix[col][row] = ma...
Python
1
info( f"GRPC invoke {context.controller_method.name}({message_to_str(request)}) " f"[OK] {context.elapsed_time} ms" ) class StreamStreamMethod(UnaryStreamMethod): """Implementation of a stream-stream gRPC method (streaming request, streaming response).""" mode = MethodMode.STR...
Python
1
BLOCKING_VEHICLES = 37 TL_COMPLETE_DEFINITION_RYG = 43 TL_COMPLETE_PROGRAM_RYG = 44 TL_CONTROLLED_JUNCTIONS = 42 TL_CONTROLLED_LANES = 38 TL_CONTROLLED_LINKS = 39 TL_CURRENT_PHASE = 40 TL_CURRENT_PROGRAM = 41 TL_EXTERNAL_STA...
Python
1
path.join(best_save_path, 'best_{}.pth'.format(0)))) sd = model.state_dict() for i in range(1,args.n_average_model): model.load_state_dict(torch.load(os.path.join(best_save_path, 'best_{}.pth'.format(i)))) print('Model loaded : {}'.format(os.path.join(best_save_path, 'best_{}.pth...
Python
1
import os import numpy as np import torch from torch.autograd import Function try: import raymarch_cuda except Exception as e: print('please build extensions/ngp_raymarch for NGPGridSampler') class _update_bitfield(Function): @staticmethod def forward(ctx, density_grid, density_grid_mean, density_gr...
Python
1
ge::Identity::new( name.to_string(), Inlet::new(name.clone(), PORT_DATA), Outlet::new(name.clone(), PORT_DATA), ); Self::with_transform(name, policy, identity).await } } impl<T, C, D> PolicyPhase<T, T, C, D> where T: AppData + ToPolar, C: ProctorContext, ...
Rust
0
!("8otpHxrRhyCsYXx5JZyHscYD3eZu1ujzjFDXPctqYFHd"); // basic anchor definition // #[program] is where the function for the logic of the program is written // #[derive(Accounts)] is where is put our structs // #[account] #[program] pub mod myepicproject { use super::*; pub fn start_stuff_off(ctx: Context<StartStuf...
Rust
0
ppingPage: """ Retrieve a specific page of IpAccessControlListMappingInstance records from the API. Request is executed immediately :param target_url: API-generated URL for the requested results page :returns: Page of IpAccessControlListMappingInstance """ respo...
Python
1
(visible as u8)).expect("set isVisible value"); } if digit.decimal.is_some() { let decimal = digit.decimal.unwrap(); env.set_field(digit_class_obj, "decimal", "I", JValue::Int(decimal as i32)).expect("set decimal value"); } if digit.imgurl.is_some() { ...
Rust
0
import cv2 import numpy as np from paddleocr import PaddleOCR from moviepy.video.io.VideoFileClip import VideoFileClip import difflib # Khởi tạo OCR với ngôn ngữ Trung (ch) ocr = PaddleOCR(lang='ch') # Đường dẫn video video_path = 'input.mp4' clip = VideoFileClip(video_path) # Thông số video video_fps = clip.fps # ...
Python
1
template_system_general_summary = """ Eres un modelo avanzado de inteligencia artificial especializado en generar resúmenes claros, concisos y organizados de cualquier tipo de contenido. Tu objetivo es procesar la información proporcionada y generar un resumen estructurado que destaque los puntos clave. 1. **Instruc...
Python
1
64, /// Output only. The actual training cost of the model, expressed in milli /// node hours, i.e. 1,000 value in this field means 1 node hour. Guaranteed /// to not exceed the train budget. #[prost(int64, tag="7")] pub train_cost_milli_node_hours: i64, /// Use the entire training budget. This ...
Rust
0
print("Count to 10!") for x in range (0, 11): print(x)
Python
1
intercepted_handler = self.interceptor.intercept_service( continuation, handler_call_details ) expected_logs = self.get_expected_logs(expected_method_name) # Execute: Invoke the intercepted unary_unary method dummy_request = MagicMock() dummy_context = MagicMo...
Python
1
lif action == "reschedule": SHEET.update_cell(row, 5, "Reschedule Requested") await query.message.reply_text("♻ Reschedule requested. User asked to select a new date/time.") if user_id: await context.bot.send_message( chat_id=user_id, ...
Python
1
from typing import Union import torch class Timesteps: """ Sampling timesteps. It defines the discretization of sampling steps. """ def __init__( self, T: int, steps: int, device: torch.device = "cpu", ): self.T = T timesteps = torch.arange(T, -...
Python
1
# main.py - A playground for experimenting with Python code def hello_world(): """Simple function to print 'Hello, World!'""" print("Hello, World!") def fibonacci(n): """Generate the first n numbers of the Fibonacci sequence""" fib_sequence = [0, 1] while len(fib_sequence) < n: fib_sequenc...
Python
1
#Decode the string class Solution: def decodedString(self, s: str) -> str: # The stack will store tuples of (string_so_far, repetition_count) # for each level of nesting. stack = [] current_num = 0 current_str = "" for char in s: if char.isdigit(): ...
Python
1
it loader = unittest.TestLoader() suite = loader.loadTestsFromTestCase(TestEPUBTranslator) runner = unittest.TextTestRunner(verbosity=2) result = runner.run(suite) if result.wasSuccessful(): print("✅ All unit tests passed!") else: print("⚠️ Some u...
Python
1
imizer variables for var in optimizer.variables(): var.assign(tf.zeros_like(var)) loss_weights = None weighted_metrics = None if self.model.compiled_loss: loss_weights = self.model.compiled_loss._loss_weights # pylint: disable=W0212 if self.model.compile...
Python
1
} /** * [0433] Minimum Genetic Mutation * * A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'. * Suppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene s...
Rust
0
# -*- coding: utf-8 -*- """ Noise Frequency Spectrum Analysis v1.0 Lukas Kostal, 17.3.2024, ICL """ import numpy as np import matplotlib.pyplot as plt import scipy.signal as ss import scipy.optimize as so import scipy.fft as sf import scipy.integrate as si def res(x, a0, a1, fsr): y = a0 / (1 + a1 * (np.sin(np...
Python
1
>|>[rLNrrwidthAwidthBlengthAlengthBrrscaleAscaleB_beginarrow_head_beginarrow_bracket_endarrow_head_endarrow_bracketarrowrr fillbeginfillendrArB)r[rrrFrGrHrIrrrJrK beginarrowendarrowr]s r^rBArrowStyle._Curve.__init_...
Python
1
pub use self::sample::*; #[doc(inline)] pub use self::surface::*; #[doc(inline)] pub use self::swap_chain::*; mod adapter; mod dbool; mod frame_statistics; mod fullscreen; mod gamma_control; mod luid; mod mode; mod output; mod present_parameters; mod query_video_memory_info; mod ratio; mod rgb; mod sample; mod surfac...
Rust
0
readdir( &mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, mut reply: ReplyDirectory, ) { if let Ok(runtime) = self.runtime.lock() { let metadata = self.metadata.clone(); if let Some(results) = runtime.block_on(async mov...
Rust
0
""" Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, using read function and display those words, which are less than 4 characters. """ print("Hey!! You can print the word which are less then 4 characters") def display_words(file_path): try: with open(...
Python
1
rpc_internal_error, rpc_invalid_arg_error, send_result, ConnectionUriGrpcioServer, }; use mc_util_uri::{ConsensusClientUri, Uri, UriScheme}; use std::{ convert::TryFrom, str::FromStr, sync::{Arc, Mutex}, thread::sleep, time::Duration, }; use structopt::StructOpt; /// Remote Wallet Uri Scheme #[deri...
Rust
0
svg::node::element::Rectangle::new() .set(X_ATTR, -(self.size as i32)) .set(Y_ATTR, -(self.size as i32)) .set(WIDTH_ATTR, 2 * self.size) .set(HEIGHT_ATTR, 2 * self.size) ...
Rust
0
thickness, wall_thickness)), ..Default::default() }) .with(Collider::Death) .with(Parent(root)); // top commands .spawn(SpriteBundle { material: wall_material, transform: Transform::from_translation(Vec3::new(0.0, bounds.y / 2.0, 0.0)), ...
Rust
0
lete // taken from https://github.com/rust-lang/rust/issues/70507#issuecomment-615268893 struct Foo; impl Foo { fn foo<const N: usize>(self) {} } fn main() { Foo.foo(); //~^ ERROR type annotations needed } <gh_stars>0 //! Read or write formatted data to a text stream. use escape_string::split_one; use cra...
Rust
0
import pandas as pd import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import os df = pd.read_excel('C:/academy_reports/academy_reports/sessions/weight/weight.xlsx') df.to_csv('C:/academy_reports/academy_reports/sessions/weight/weight.csv', encoding='utf-8', index=False) path = "C:/a...
Python
1
(format!( "Access to Move global storage is not allowed. Found in function {}: {:?}", view.identifier_at(view.function_handle_at(func_def.function).name), invalid_bytecode, ))); } } Ok(()) } <gh_stars>1-10 use lazy_static::lazy_static; use std:...
Rust
0
_javascript::JSX_HIGHLIGHT_QUERY.to_owned(); highlights.push_str(tree_sitter_javascript::HIGHLIGHT_QUERY); let mut config = HighlightConfiguration::new( tree_sitter_javascript::language(), &highlights, tree_sitter_javascript::INJECTION_QUERY, tree_sitter_javascript::LOCALS_QUERY, )....
Rust
0
needed url = _get_redirect_url(url, max_hops=max_redirect_hops) # # check if file is located on Google Drive # file_id = _get_google_drive_file_id(url) # if file_id is not None: # return download_file_from_google_drive(file_id, root, filename, md5) # download the file try: pri...
Python
1
fn as_any(&self) -> &dyn std::any::Any { self } } impl Normal { pub fn new() -> Normal { Normal { count_state: cmd_count::State::None, } } } impl Solution { fn find_min_s(nums: &[i32]) -> i32 { match nums.len() { 0 => 0, 1 => nums...
Rust
0
v)| -> PyResult<_> { let (key, value) = ( PyPathLike::try_from_object(vm, k)?.into_bytes(), PyPathLike::try_from_object(vm, v)?.into_bytes(), ); if memchr::memchr(b'=', &key).is_some() { return Err(vm.new_value_...
Rust
0
"""This directory contains helper scripts for the ImagesStockScraper project."""
Python
1
from fastapi import Depends, HTTPException, status from sqlalchemy.orm import Session import logging from app.database.database import SessionLocal from app.database.models.models_database import Usuario, Tipo_Usuario logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def get_db(): db ...
Python
1
distr_int!($group, $name, u64, Binomial::new($n, $p).unwrap()) }; } fn bench(c: &mut Criterion<CyclesPerByte>) { { let mut g = c.benchmark_group("exp"); distr_float!(g, "exp", f64, Exp::new(1.23 * 4.56).unwrap()); distr_float!(g, "exp1_specialized", f64, Exp1); distr_float!(g, "exp1_general", f...
Rust
0
y 2") axes[4].set_axis_off() axes[4].text( 0.5 * (left + right), 0.5 * (bottom + top), ("Using a pure\nGaussian distribution"), horizontalalignment="center", verticalalignment="center", fontsize=20, color="black", transform=axes[4].transAxes, ) axes[5].plot(mesh.cell_centers_x, wires.m...
Python
1
#!/usr/bin/env python3 # Copyright (C) 2018 Federico Pellegrin <fede@evolware.org> # Copyright (C) 2019 Francisco Molina <francois-xavier.molina@inria.fr> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more det...
Python
1
import scallopy import re @scallopy.foreign_function def crop_image( img: scallopy.Tensor, bbox_x: scallopy.u32, bbox_y: scallopy.u32, bbox_w: scallopy.u32, bbox_h: scallopy.u32, loc: str = None, ) -> scallopy.Tensor: img_h, img_w, _ = img.shape # Clip bounding box x1, y1, x2, y2 = min(bbox_x, img_w...
Python
1
10) jq.run_repeating(check_datacenters_job, interval=60, first=15) # 启动机器人! logger.info("机器人启动中,开始轮询... (按 Ctrl+C 停止)") application.run_polling(drop_pending_updates=True) async def cleanup(application): logger.info("开始关闭程序...") if application.updater and application.updater.is_running: ...
Python
1
import unittest import sys sys.path.append( "src" ) from model.tarjeta import Tarjeta from controller.tarjetas_controller import TarjetasController class TestTarjeta( unittest.TestCase ): def setUpClass(): """ Test Fixtures que se ejecuta al inicio de las pruebas solamente""" TarjetasController.b...
Python
1
import functools import inspect @functools.lru_cache(maxsize=512) def _get_func_parameters(func, remove_first): parameters = tuple(inspect.signature(func).parameters.values()) if remove_first: parameters = parameters[1:] return parameters def _get_callable_parameters(meth_or_func): is_method...
Python
1
r count in range(cr[0], cr[1] + 1): for comb in itertools.combinations(vari, count): values.append(sep.join(comb)) return values return replacer replacers.append(make_replacer_enum(variants, count_range, separator)) ...
Python
1
pd.read_csv('spotify_tracks.csv') yt_df = pd.read_csv('yt_tracks.csv') # Extract only the 'name' column (or the corresponding column name) spotify_names = spotify_df['name'] yt_names = yt_df['name'] # Find tracks that are in Spotify but not in YouTube Music not_in_yt = spotify_df[~spotify_df['name'].isin(yt_names)].d...
Python
1
usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( tdTPM_DELEGATE_KEY_BLOB ) , "::" , stringify ! ( tag ) )); assert_eq! (unsafe { & ( * ( 0 as * const tdTPM_DELEGATE_KEY_BLOB ) ) . pub_ as * const _ as usize } , 8usize , concat ! ( ...
Rust
0
import my import tp def tp_init(name): self = tp.Tp(name, "small ripple", "small ripple") # begin sort marker my.gfx_ascii_shown(self, True) my.gfx_pixelart_animated(self, True) my.gfx_pixelart_reflection(self, True) my.gfx_pixelart_shadow(self, True) my.is_one_per_tile(self, True) my....
Python
1
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" from __future__ import annotations import pydantic from pydantic import model_serializer from typing import List, Optional from typing_extensions import Annotated, NotRequired, TypedDict from unstructured_client.types import ( BaseModel, N...
Python
1
pin!(DA0Pin); declare_pin!(DA1Pin); declare_pin!(DA2Pin); declare_pin!(DA3Pin); declare_pin!(DA4Pin); declare_pin!(DA5Pin); declare_pin!(DA6Pin); declare_pin!(DA7Pin); declare_pin!(DA8Pin); declare_pin!(DA9Pin); declare_pin!(DA10Pin); declare_pin!(DA11Pin); declare_pin!(D...
Rust
0
(0) assert isinstance(hash(wf), int) mystdout = StringIO() p = PP(mystdout) wf2._repr_pretty_(p, 2) assert ( mystdout.getvalue() == "Sample linear\n" + "├─ Waveform\n" + "│ ⇒ PythonFn: my_cos\n" + "│ └─ duration\n" + "│ ⇒ Literal: 1.0\n" ...
Python
1
= new_values; } } impl Display for Paper { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { for r in 0..self.rows() { for c in 0..self.cols() { if self.values[r * self.cols() + c] { write!(f, "# ")?; } else { ...
Rust
0
from django.contrib.gis.db import models as gis_models from django.db import models from django.utils.translation import gettext_lazy as _ from django_softdelete.models import SoftDeleteModel from apps.location.constants import LocationNameChoices from apps.location.models.country import Country from apps.users.models...
Python
1
T": menu_id = res_dir.get("id") if id: menu = Menu.query.get(menu_id) if menu: menu_data = model_to_dict(menu) return SUCCESS(menu_data) else: return ID_NOT_FOUND() else: PARAMETER_ERR() if reques...
Python
1
map(|raw_accept_language| { accept_language::parse(raw_accept_language) .iter() .filter_map(|al| parse_language_identifier(al.as_bytes()).ok()) .collect() }) .unwrap_or_else(Vec::new); AcceptLanguage { accept_language, } } #[r...
Rust
0
; pub static REV_ACTIONS_DIR: &str = "/usr/libexec/keylime"; pub static REV_ACTIONS: &str = ""; pub static ALLOW_PAYLOAD_REV_ACTIONS: bool = true; // Secure mount of tpmfs (False is generally used for development environments) #[cfg(not(feature = "testing"))] pub static MOUNT_SECURE: bool = true; #[cfg(feature = "tes...
Rust
0
} // // Implement Pack trait // impl Pack for Hello { // Fixed length const LEN: usize = 4; // Unpack data from [u8] to the data struct fn unpack_from_slice(src: &[u8]) -> Result<Self, ProgramError> { let src_times = array_ref![src, 0, 4]; let times = u32::from_le_bytes(*src_times); Ok(Hello { time...
Rust
0
f { Term::OtherOp(op) } } impl<T: Logic> From<IUF<T>> for Term<T> { fn from(op: IUF<T>) -> Self { Term::UF(op) } } impl<T: Logic> From<ILet<T>> for Term<T> { fn from(l: ILet<T>) -> Self { Term::Let(l) } } impl<T: Logic> From<IMatch<T>> for Term<T> { fn from(m: IMatch<T...
Rust
0
(map(str, common_free_days))}") else: await update.message.reply_text("Group data not available for this chat.") ### ERROR HANDLING async def context_error(update: Update, context: ContextTypes.DEFAULT_TYPE): print(f'Update {update} caused context error {context.error}') ### START BOT if __...
Python
1
" Compressed %.2f MB with %d pool threads, %d blosc threads in: %f s" \ % ( MegaBytes, 0, bloscThreads[I], solo_times[I]) ) print( "##### NO PYTHON THREADPOOL -- GIL RELEASED #####" ) print( " -- Shows penalty for releasing GIL in normal blosc operation --" ) for I in np.arange( len(poolThreads) ): print( ...
Python
1
# -*- python -*- # # Copyright (C) 2005, 2006 Mekensleep <licensing@mekensleep.com> # 24 rue vieille du temple, 75004 Paris # # This software's license gives you freedom; you can copy, convey, # propagate, redistribute and/or modify this program under the terms of # the GNU Affero General Publi...
Python
1
, check_moment_span!(c, [2013, 2, 11, 4], [2013, 2, 12, 4]), "last 24 hours", "last twenty four hours", "last twenty four hrs", "last 24 hrs", "last 24hrs"); // example!(v, check_moment_span!(c, [2013, 2, 12, 5], [2013, 2, 12, 8]), "next 3 hours", "next three hours"); // example!(v, check_moment_span!(c, [2013,...
Rust
0
2 { uint::from_str(args[1]).get() } else { 100 // woefully inadequate for any real measurement } }; let seed = ~[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; { let rng = rand::seeded_rng(&seed); let mut results = empty_results(); int_benchmarks::<map::Ha...
Rust
0
size.width, 0.5)), data.config.get_color_unchecked(LapceTheme::LAPCE_BORDER), 1.0, ); for btn in self.buttons.iter() { ctx.stroke( &btn.rect, data.config.get_color_unchecked(LapceTheme::LAPCE_BORDER), 1.0, ...
Rust
0
 d<Xc@`sgddlmZmZmZddlmZmZddlmZmZm Z m Z m Z dZ dS(i(tabsolute_importtdivisiontunicode_literals(tQNametAttrs(tSTARTtENDtTEXTtCOMMENTtDOCTYPEcc`sg}x|D]}|...
Python
1
f.base_url super(HTMLTagProcessor, self).__init__(**kwargs) def process(self, value, instance, field, **kwargs): def renderer(): context = { 'value': value, 'instance': instance, 'field': field, } if self.ba...
Python
1
= None _TESTUNPACKEDTYPES.fields_by_name['unpacked_enum']._options = None _TESTDYNAMICEXTENSIONS.fields_by_name['packed_extension']._options = None _TESTHUGEFIELDNUMBERS_STRINGSTRINGMAPENTRY._options = None _TESTHUGEFIELDNUMBERS.fields_by_name['repeated_int32']._options = None _TESTHUGEFIELDNUMBERS.fields_by_name['pac...
Python
1
f32, croppa: 0f32, magnite: 0f32, umanite: 0f32 } } } impl Minerals { fn new(bismor: f32, enor: f32, jadiz: f32, croppa: f32, magnite: f32, umanite: f32) -> Minerals { Minerals { bismor, enor, jadiz, cro...
Rust
0
n. """ ### # Create the application and read the host and port addresses # app = create_app() host = server_option("host") port = int(server_option("port")) ### # Access Log Format (Will not work with the dev server(for now)) # # %a: Remote IP-address # %r: First line of...
Python
1
########################################################################## # # Copyright (c) 2007-2011, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redis...
Python
1
tx.clone())?; Ok(Mixer { sources: RwLock::new(HandlePool::new()), tx: tx, clips: clips, }) } } impl Drop for Mixer { fn drop(&mut self) { let cmd = Command::Discard; self.tx.write().unwrap().push(cmd); } } impl Mixer { #[inline] ...
Rust
0
ing> { self.priority.partial_cmp(&other.priority) } } impl<T, U> PartialEq for PriorityQueueItem<T, U> where T: Ord + PartialOrd + Eq { fn eq(&self, other: &Self) -> bool { self.priority.eq(&other.priority) } } impl<T, U> Eq for PriorityQueueItem<T, U> where T: Ord + PartialOrd + Eq {} im...
Rust
0