text
string
label_name
string
labels
int64
from collections import deque def get_neighbors(grid, row, col, visited): neighbors = [] for r, c in ((row-1, col-1), (row-1, col+1), (row+1, col-1), (row+1, col+1)): if 0 <= r < len(grid) and 0 <= c < len(grid) and grid[r][c] == 0 and (r, c) != (row, col) and (r, c) not in visited: neighb...
Python
1
QueuesQueryClosure<F>(pub F); impl<F, Q, E> QueuesQuery for QueuesQueryClosure<F> where F: FnOnce(&[FamilyInfo]) -> Result<Q, E>, Q: IntoIterator<Item = (usize, usize)>, E: Error + 'static, { type Collector = (); type Error = E; type Query = Vec<(usize, usize)>; type Queues = Vec<Family>; ...
Rust
0
""" This module contains the unit tests for the Python modules. """
Python
1
# String examples name = "Abdul Basit" print(name.upper()) # uppercase print(name.lower()) # lowercase print(name.title()) # title case print(name.find("A")) # index of A print(name.find("Basit")) # index of substring print(name.replace("Abdul Basit", "Mansab Abro")) # replace string pri...
Python
1
fn from(e: io::Error) -> Self { Self::ServerDeserialize(e.to_string()) } } impl ToString for WireError{ fn to_string(&self) -> String { match self{ WireError::ClientDeserialize(e) => {e.to_owned()} WireError::ServerDeserialize(e) => {e.to_owned()} WireError:...
Rust
0
// set backreference unsafe { (*red_node).root = root_ptr; } TreeArc { inner: red_node } } #[cold] fn new_child( &self, start_offset: TextUnit, index_in_parent: SyntaxIndex, index_in_green: GreenIndex, green: GreenNode, ...
Rust
0
rect_vc = rect_to_vc_rect(image_resource.image.get_src_rect()); let handle = dispmanx::element_add(self.handle, self.display.handle, layer, &mut dest_rect_vc, image_resource.resource, &mut src_rect_vc, dispmanx::DISPMANX_PROTECTION_NONE, &mut NO_ALPHA, ptr::null_mut(), dispmanx::Transform::NO_ROTATE); E...
Rust
0
from lc import * class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: v = set() q = [] q.append(0) while q: i = q.pop() if i not in v: v.add(i) q += rooms[i] return len(v)==len(rooms) class Solut...
Python
1
Obtain Own State */ pub fn get_state(&self) -> CANOpenState { return self.state; } pub fn get_state_u8(&self) -> u8 { return canopen_state_val(self.state); } /* Set Internal State */ pub fn set_state(&mut self, state: CANOpenState) { self.state = state; } /* D...
Rust
0
lap_uv_ids, seg_ids).all(axis=1) if valid_uv_ids.sum() == 0: continue overlap_uv_ids, overlap_values = overlap_uv_ids[valid_uv_ids], overlap_values[valid_uv_ids] assert len(overlap_uv_ids) == len(overlap_values) # Get the edge ids. edge_ids = ...
Python
1
f"Query params: {len(query_params)}") logger.debug(f"Keywords: {keywords}") cur.execute(query_sql, query_params) results = cur.fetchall() filtered_results = [] for row in results: try: # 메타데이터에 c...
Python
1
p(); static ref OPEN_SANS_ITALIC: Font<'static> = Font::from_bytes(include_bytes!("../fonts/opensans/OpenSans-Italic.ttf") as &[u8]).unwrap(); } fn draw_luma_alpha(glyph: ScaledGlyph<'_>) -> image::GrayAlphaImage { let glyph = glyph.positioned(point(0.0, 0.0)); let bounds = glyph.pixel_bounding_box...
Rust
0
O_BIT); } else { self.unset_flag_bit(ZERO_BIT); } if result & 0x0F == 0x0F { self.set_flag_bit(HALF_CARRY_BIT); } else { self.unset_flag_bit(HALF_CARRY_BIT); } return result; } fn rotate_left(&mut self, value: u8, is_prefixed...
Rust
0
if not portfolio_df.empty: # Format the DataFrame for display display_df = portfolio_df.copy() display_df['market_value'] = display_df['market_value'].map('${:,.2f}'.format) display_df['current_price'] = display_df['current_price'].map('${:.2f}'...
Python
1
tts.write_to_fp(fp) fp.seek(0) # Save and play with pygame with open("temp_audio.mp3", "wb") as f: f.write(fp.read()) mixer.init() mixer.music.load("temp_audio.mp3") mixer.music.play() # Chat interface st.markdown("### 📝 Your Message") col1, col2 = st.columns([6, 1]) with co...
Python
1
""" API连接调试工具 帮助诊断和解决API连接问题 """ import json import http.client import ssl from urllib.parse import urlparse def test_api_detailed(api_key: str, base_url: str, model: str): """详细的API测试""" print("🔍 开始详细API测试...") print(f"📍 API URL: {base_url}") print(f"🤖 模型: {model}") print(f"🔑 API Key: {api_k...
Python
1
Request::Destroy; self.0.send::<AnonymousObject>(msg, None); } #[doc = "grab the keyboard to a surface\n\nThe grab_keyboard request asks for a grab of the keyboard, forcing\nthe keyboard focus for the given seat upon the given surface.\n\nThe protocol provides no guarantee that the grab is ...
Rust
0
load_file(dataset_url, zipped_dataset_path) __extract_file(zipped_dataset_path, dataset_root) # generate train/dev/test splits unzipped_dataset_path = dataset_root / THORSTEN_NEUTRAL[data_version]["dir_name"] entries_train, entries_val, entries_test, not_found_wavs, wrong_duration_wavs = __process_data...
Python
1
ult { blocked: BlockedStatus::Blocked, action_result: ActionResult::with_actions(vec![Action::SendBoardMessage(BoardMessage::ShowOneTimeNotification(OneTimeNotification::BlockedByWater))]), } } else { PushResult::do_nothing_blocked() } } fn blocked_for_bullets(&self) -> BlockedStatus { BlockedSta...
Rust
0
#!/usr/bin/env python # Copyright (c) 2021-2025, Arm Limited # SPDX-License-Identifier: Apache-2.0 # # 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/LICEN...
Python
1
/rtccntl/rtc_cntl_slp_reject_conf.rs<gh_stars>0 #[doc = "Reader of register RTC_CNTL_SLP_REJECT_CONF"] pub type R = crate::R<u32, super::RTC_CNTL_SLP_REJECT_CONF>; #[doc = "Writer for register RTC_CNTL_SLP_REJECT_CONF"] pub type W = crate::W<u32, super::RTC_CNTL_SLP_REJECT_CONF>; #[doc = "Register RTC_CNTL_SLP_REJECT_C...
Rust
0
from llama_index.readers.mondaydotcom.base import MondayReader __all__ = ["MondayReader"]
Python
1
RandomR (0, 1) // b' <- getRandomR (0, 1) // let (a, b) = if a' + b' > 1 then (1 - a', 1 - b') else (a', b') // return $ v1^.core .+^ a*^u .+^ b*^v // where // u = v2^.core .-. v1^.core // v = v3^.core .-. v1^.core } //! A world, where entities live //! //! By default, all entities should l...
Rust
0
T_COLLECTION, path=TEST_PATH, embedder=mock_embedder) db.create() assert db.embedder == mock_embedder # Cleanup try: db.drop() finally: if os.path.exists(TEST_PATH): shutil.rmtree(TEST_PATH) def test_multiple_document_operations(chroma_db, sample_documents): """Tes...
Python
1
(), _ => Err(DeError::new("Failed to find specified attribute")), } } } #[cfg(test)] mod test { use super::*; use crate::{ consts::{ nl::{NlmF, NlmFFlags}, socket::NlFamily, }, nl::{NlPayload, Nlmsghdr}, socket::NlSocketHandle, ...
Rust
0
pool: pool.clone(), graph: pool.pool().clone(), deny_unsafe, is_authority: collator, network: network.clone(), pending_transactions: pending.clone(), filter_pool: filter_pool.clone(), ethapi_cmd: ethapi_cmd.clone(), command_sink: command_sink.clone(), frontier_backend: frontier_ba...
Rust
0
/env python import sys print(sys.executable) """ ) from robocorp_code._language_server_pre_run_scripts import _PreRunScripts pre_run_scripts = _PreRunScripts(NULL) assert pre_run_scripts._has_pre_run_scripts_internal(params={"robot": str(tmpdir)}) env = get_env() path = env["PATH"] env["P...
Python
1
124-.065-.224v-.448zm1.471.01h.193c.082 0 .146.019.19.056.044.038.065.093.065.165 0 .067-.025.121-.075.161s-.119.059-.207.059c-.011 0-.03-.001-.055-.002h-.002v.288l-.109.009zm.109.096v.244l.03.003c.011.002.022.002.036.002.053 0 .093-.01.12-.032.028-.021.042-.051.042-.092 0-.043-.013-.074-.038-.094s-.065-.031-.119-...
Python
1
""" Utility functions for prompt linking in trace exporters. """ import logging import threading import uuid from typing import Sequence from mlflow.entities.model_registry import PromptVersion from mlflow.tracing.client import TracingClient _logger = logging.getLogger(__name__) def try_link_prompts_to_trace( ...
Python
1
evice): res = np.zeros((1402, 7), dtype = np.float32) for model in models_arr: model.eval() res_arr = [] for inputs, inputs_area, inputs_mask, _ in loader: inputs = inputs.to(device) inputs_mask = inputs_mask.to(device) inputs_area = inputs_area.to(dev...
Python
1
r_k1_xmm_xmmm128b32", "EVEX_Vpcmpeqd_kr_k1_ymm_ymmm256b32", "EVEX_Vpcmpeqd_kr_k1_zmm_zmmm512b32", "Emms", "VEX_Vzeroupper", "VEX_Vzeroall", "Vmread_rm32_r32", "Vmread_rm64_r64", "EVEX_Vcvttps2udq_xmm_k1z_xmmm128b32", "EVEX_Vcvttps2udq_ymm_k1z_ymmm256b32", "EVEX_Vcvttps2udq_zmm_k1z_zmmm512b32_sae", "EVEX_Vcvt...
Rust
0
Stone `st` (`14lb`) or (`6.35029318kg`). pub static STONE: Derived = Derived { id: crate::generated::ids::STONE, vtable: &DerivedVtable { powers: |powers, p| { powers.insert(Unit::KiloGram, p); }, format: |f, _| write!(f, "st"), conversion: Some(Conversion::Factor(Co...
Rust
0
_iter(self) -> NodeIter<'a> { let mut queue: VecDeque<NodeRef> = VecDeque::new(); queue.push_back(NodeRef::Group(self)); NodeIter { queue } } } use crate::{concat_reaper_strs, ReaperStr, ReaperStringArg}; use std::borrow::Cow; /// Track attribute key which you can pass to [`get_set_media_...
Rust
0
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. # # 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 appli...
Python
1
rser.add_argument('--input_dir', help='Directory to find input tars', default=None) parser.add_argument('--out_dir', help='Directory to write ingested files', default=None) parser.add_argument('--target_size', type=int, default=256, help='Size in pixels to scale shortest side DOWN to (0 ...
Python
1
'float', 'for', 'goto', 'if', 'inline', # (C99) 'int', 'long', 'nullptr', # (C23) 'register', 'restrict', # (C99) 'return', 'short', 'signed', 'sizeof', 'static', 'static_assert', # (C23) 'struct', 'switch', 'thread_local', # (C23) 'tru...
Python
1
import numpy as np def cartesian2spherical(cartesian): """Convert cartesian to spherical coordinates Args: cartesian (ndarray): Vector (x, y, z) Returns: spherical (ndarray): Vector (distance, azimuth, elevation) """ cartesian = np.array(cartesian).squeeze() x, y, z = cartesi...
Python
1
rotein_graph.x, ligand_graph.x], dim=0), edge_index=torch.cat([protein_graph.edge_index, ligand_graph.edge_index + len(protein_graph.x)], dim=1), edge_attr=torch.cat([protein_graph.edge_attr, ligand_graph.edge_attr], dim=0) ) print(f"✅ Combined Graph Created: {protein_ligand_graph.x.shape[0]} n...
Python
1
d_data, valid_labels, valid_segment) var_w = performance_diff( filtered_model, unfiltered_model, valid_non_device_data, valid_non_device_labels, perf_function=self.perf_func, ) if self.eps < var_w: ...
Python
1
0; } } current_nesting -= 1; } quick_xml::events::Event::Eof => break, e => write_event(&mut contexts, context_idx, e)?, } } Ok(()) } #![cfg(target_pointer_width = "64")] use std::mem; use syn::{Expr, Item, Lit, Pa...
Rust
0
pretrained_weights(model, model_urls["resnet50"]) return model @BACKBONE_REGISTRY.register() def resnet101_efdmix_l123(pretrained=True, **kwargs): from dassl.modeling.ops import EFDMix model = ResNet( block=Bottleneck, layers=[3, 4, 23, 3], ms_class=EFDMix, ms_layers=["la...
Python
1
import bpy from bpy.types import Context, Collection from ..plumber import Light, SpotLight, EnvLight def import_light(light: Light, collection: Collection) -> None: name = f"light_{light.id()}" light_data = bpy.data.lights.new(name, "POINT") light_data.cycles.use_multiple_importance_sampling = False ...
Python
1
color='tab:orange') # ax2.set_ylim(0, 1) # ax2.tick_params(axis='y', labelcolor='tab:orange') # # Titre, axe x, légende combinée # plt.title("Évolution des métriques de qualité (PSNR, SSIM, PCC, STD)") # ax1.set_xlabel("Époque") # # Combine les légendes des deux axes # lines_1, labels_1 = ax1.get_legend_handles_labe...
Python
1
", &self.glGetAttachedShaders_p, program, maxCount, count, shaders, ); #[cfg(all(debug_assertions, feature = "debug_automatic_glGetError"))] { self.automatic_glGetError("glGetAttachedShaders"); } out } #[doc(hidden)] pub unsafe fn...
Rust
0
int(retry_attempts), int(llm_schema_retries), ) def _compute_effective_preset( selected_preset: str, controls: PresetControls, ) -> str: """ Compute whether the current controls still match the selected preset. Returns: str: The effective preset, or "Custom" if controls...
Python
1
(&self, id_from: u16, code: co::NM, func: F) where F: FnMut(wm::Notify) -> isize + 'static, { self.add_nfy(id_from, code, { let mut func = func; move |p| Some(func(p)) // return value is meaningful }); } wm_ret_none! { wm_activate, co::WM::ACTIVATE, wm::Activate, /// [`WM_ACTIVATE`](crate::m...
Rust
0
import unittest from unittest.mock import AsyncMock, patch from mage_ai.authentication.providers.oidc import OidcProvider class OidcProviderTest(unittest.IsolatedAsyncioTestCase): async def test_get_user_info(self): # Define test cases test_cases = [ { 'user_roles': ['...
Python
1
e=None, tipRadius=float(i.get("radius", 0)) * 1e6, # m -> um tipWallThickness=float(i.get("wallThickness", 0)) * 1e6, # m -> um ).items(): if k not in i: i[k] = v if i.method == "calculation" and i.meth...
Python
1
erty, } => { if let FieldKind::Object(ref value) = property.value { match property.name.as_ref() { LevelOfDetail::BEGIN => { helper.do_scene_command(ChangeLodRangeBeginCommand::new...
Rust
0
bKitGradientPointComponent::*; match &self { Center => { if dest.minify { dest.write_str("50%") } else { dest.write_str("center") } } Number(lp) => { if matches!(lp, NumberOrPercentage::Percentage(Percentage(p)) if *p == 0.0) { dest.wri...
Rust
0
Error, DeleteError, IOError, } impl From<std::io::Error> for BlobStorageError { fn from(error: std::io::Error) -> Self { BlobStorageError::IOError } } /// Blob References are used to reference previously stored blobs. #[typetag::serde(tag = "type", content = "payload")] pub trait BlobRef { ...
Rust
0
_elision, AtomicElisionExt}; use crate::raw_mutex::{TOKEN_HANDOFF, TOKEN_NORMAL}; use crate::util; use core::{ cell::Cell, sync::atomic::{AtomicUsize, Ordering}, }; use instant::Instant; use lock_api::{RawRwLock as RawRwLock_, RawRwLockUpgrade}; use parking_lot_core::{ self, deadlock, FilterOp, ParkResult, ...
Rust
0
n self.listdict.values() def items(self): return self.listdict.items() # def save(self,save_file): # raise NotImplementedError def log_setup(setup, setups_file): """ update an exisiting CSV file or create new one if not exisiting using setup """ setup_ld = ListDict(setup) i...
Python
1
" { pub fn getpriority(arg1: ::std::os::raw::c_int, arg2: id_t) -> ::std::os::raw::c_int; } extern "C" { pub fn getiopolicy_np( arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int; } extern "C" { pub fn getrlimit(arg1: ::std::os::raw::c_int, arg2: *mut rl...
Rust
0
number = input("Enter a number: ") try: number = float(number) # Convert input to a float if number > 0: print("The number is positive.") elif number < 0: print("The number is negative.") else: print("The number is zero.") except ValueError: print("Invalid input. Please e...
Python
1
sub_logit) sub_predictions.append( [ category.decode(index) for index in sub_logit.argmax(dim=-1).detach().cpu().tolist() ] ) logit_start = logit_end prediction = np.array(sub_predictions, dtype="object")...
Python
1
use std::mem; use crate::Shape; /// A 2-dimensional shape #[derive(Clone, Debug)] #[repr(C)] pub enum Shape2d { /// A circle Circle(Circle), /// A difference between two shapes Difference(Box<Difference2d>), /// A sketch Sketch(Sketch), } /// A circle #[derive(Clone, Debug)] #[repr(C)] pub...
Rust
0
] impl_trait!(OrderBook, ZbgSpotWSClient, subscribe_orderbook, "ENTRUST_ADD"); #[rustfmt::skip] impl_trait!(Ticker, ZbgSpotWSClient, subscribe_ticker, "TRADE_STATISTIC_24H"); impl_candlestick!(ZbgSpotWSClient); panic_bbo!(ZbgSpotWSClient); panic_l2_topk!(ZbgSpotWSClient); panic_l3_orderbook!(ZbgSpotWSClient); impl_ws...
Rust
0
tool process::exit(status.code().unwrap_or(101)); } /// Parses arguments for `cargo $tool` and then if needed executes `cargo build` /// before parsing the required arguments to `rust-$tool`. /// If the tool fails to start or is not found this process exits with /// status code 101 the sam...
Rust
0
me, "prev_frame": prev_frame}: # CallLogItem inside_inner_interpreter = is_internal(fn_filename) if color_internals or not inside_inner_interpreter: linecolor = colors["GREEN"] c_indent += 1 log_line = ( ...
Python
1
# Copyright 2020 The SODA 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
Python
1
import os import cv2 import json import random import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import pandas as pd import matplotlib import matplotlib.cm as cm from matplotlib import pyplot as plt from scipy.stats import pearsonr, spearmanr def setup_seed(seed): torch.manual_s...
Python
1
from typing import Optional import tensorflow as tf from debias.models.text_model import TextModel from debias.modules.attention_layers import AttentionBiFuse from debias.modules.clf_debias_loss_functions import ClfDebiasLossFunction from debias.modules.layers import SequenceMapper, PoolingLayer, Mapper from debias.m...
Python
1
= await f.create_project_role( project=project, permissions=choices.ProjectPermissions.values, is_admin=False, ) await f.create_project_membership(user=member, project=project, role=general_member_role) client.login(member) response = client.delete(f"/projects/{project.b64id}/m...
Python
1
"><!----></div></div></div> <div class="weui-desktop-mask" style="display: none;"></div></div> <!----></div></div></div> </div> </div> </div> </div> </div> <div class="mp-foot" id="footer" style="display: block;"> <div class="weui-desktop-foot"> <div class="weui-desktop-foo...
Python
1
os.path.join(train_folder, path) move(src, dst) for i in tqdm.tqdm(range(len(self.test_url_list)), desc='Preprocessing'): test_list = self.test_url_list[i].split('/')[-1] with open(os.path.join(self.root, test_list), 'r') as f: for line in f...
Python
1
import random HOROSCOPE = { "Овен": ["Сегодня отличный день для новых начинаний!", "Будьте осторожны с деньгами.", "Уделите внимание близким."], "Телец": ["День принесет вам приятные сюрпризы.", "Избегайте конфликтов на работе.", "Отдохните и восстановите силы."], "Близнецы": ["Идеальное время для общения!...
Python
1
nodes = [] seen_nodes = set() edges = [] for path in imputed_paths: for node in path: if node not in seen_nodes: unique_nodes.append(node) seen_nodes.add(node) for i in range(len(path)-1): edges.append((path[i], path[i+1])) # Out...
Python
1
xt | | | o 96a2c4be Merge commit 'fe65c1fe15584744e649b2c79d4cf9b0d878f92e' into HEAD | O 62fc20d2 (master) create test1.txt | o 96d1c37a create test2.txt | o 96a2c4be Merge commit 'fe65c1fe15584744e649b2c79d4cf9b0d878f92e' into HEAD "###); ...
Rust
0
opyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # ...
Python
1
{}: {}", filename.display(), scene); scene }, Err(desc) => { panic!("\nParsing {} failed\n\t {}", filename.display(), desc); } }; for s in scene.spheres.iter() { mat4::matrix_print(&s.transform, "Transform"); mat4::matrix_print(&s.inverse_t, "Inverse T"); } scene } #[allow(dea...
Rust
0
from pandasql.sqldf import get_outer_frame_variables, extract_table_names import pytest def test_get_vars(): var_a = 123 variable = {'a': 'b', 'c': 'd'} assert get_outer_frame_variables()['var_a'] == var_a assert get_outer_frame_variables()['variable'] == variable @pytest.mark.parametrize(('query', ...
Python
1
String, } #[derive(Clone, Debug, Hash, PartialEq, Eq)] enum FilePattern { Include(String), Exclude(String), } #[derive(Clone, Debug, Hash, PartialEq, Eq)] struct MaintainerEntry { title: String, single_word_name: String, maintainers: Vec<Maintainer>, files: Vec<FilePattern>, comments: Vec...
Rust
0
import warnings from ffmpegcv.ffmpeg_writer import FFmpegWriter from .video_info import ( run_async, get_num_QSV_GPUs, decoder_to_qsv, ) class FFmpegWriterQSV(FFmpegWriter): @staticmethod def VideoWriter(filename, codec, fps, pix_fmt, gpu, bitrate=None, resize=None, preset=None): assert gp...
Python
1
ke back on a browser */ pub const KEY_XF86Forward: u32 = 0x1008FF27; /* Like forward on a browser */ pub const KEY_XF86Stop: u32 = 0x1008FF28; /* Stop current operation */ pub const KEY_XF86Refresh: u32 = 0x1008FF29; /* Refresh the page */ pub const KEY_XF86PowerOff: u32 = 0x1008FF2A; /* Power off sy...
Rust
0
as_add(self, all_args): C, D, H, W, N, _, _, _, _, strides, padding = all_args image = tf.constant(np.random.rand(N, H, W, C).astype(np.float32)) bias = tf.constant(np.random.rand(C).astype(np.float32)) result = image + bias self.run(result, tf_feed_dict={}, rtol=1e-0, atol=1e-4)...
Python
1
import numpy as np class GaussianFeature(object): """ Gaussian feature gaussian function = exp(-0.5 * (x - m) / v) """ def __init__(self, mean, var): """ construct gaussian features Parameters ---------- mean : (n_features, ndim) or (n_features,) ndarray ...
Python
1
00:00Z let unix_time = 946684800; // Get UTC time zone let time_zone_utc = TimeZone::utc(); println!("{:?}", time_zone_utc.find_local_time_type(unix_time)?); // Get fixed time zone at GMT-1 let time_zone_fixed = TimeZone::fixed(-3600); println!("{:?}", time_zone_fixed.find_local_time_type(...
Rust
0
#!/usr/bin/python2.5 # # Copyright 2013 Emilie Gillet.. # # Author: Emilie Gillet (emilie.o.gillet@gmail.com) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, o...
Python
1
def sumDigit(n): return sum(int(i) for i in str(n)) def customSort(n): return sumDigit(n), n for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) a.sort(key=customSort) print(*a, sep=" ", end="\n")
Python
1
!(r, Err(datastore::DSError::NotFound(_)))); } } #[test] fn test_column_names() { let names = [ "/block", "/", "block", "/block/foo", "block/foo", "/block/foo/bar", "block/foo/bar", DEFAULT_COLUMN_NAME, ]; let len = names.len(); for (i...
Rust
0
""" if self.ry is not None: if hasattr(result, "optimal_point"): para_dict = dict(zip(self.ry.parameters, result.optimal_point)) unbound_para = set(self.ry.parameters) - set(para_dict.keys()) for param in unbound_para: para_dict[pa...
Python
1
def star(func): def wrapper(name): print('*'*10) func(name) print('*'*10) return wrapper @star def hello(name): print('hello ',name) # @star # def bye(): # print('hello') hello('ram') # star(hello)() # bye()
Python
1
kprint!(concat!("\x1B[31m", $fmt, "\x1B[m"), $($args)+) } else { crate::kprint!($fmt, $($args)+); } }); ($fmt:expr) => ({ if crate::kprint::COLORED { crate::kprint!(concat!("\x1B[31m", $fmt, "\x1B[m")) } else { ...
Rust
0
# -*- coding: utf-8 -*- # # Copyright (c) 2025 JD.com, Inc. All Rights Reserved # """ @File: single_task_factory.py @Date: 2025/01/09 remarks: """ from typing import Optional from config.single_task import D_SINGLE_TASK_CONFIG from task.single_task.single_task_base import SingleTaskBase from task.single_task.single_ta...
Python
1
= input.split_at(std::mem::size_of::<u64>()); // *input = rest; u64::from_be_bytes(int_bytes.try_into().unwrap()) } fn read_be_u32(input: &[u8]) -> u32 { let (int_bytes, _rest) = input.split_at(std::mem::size_of::<u32>()); // *input = rest; u32::from_be_bytes(int_bytes.try_into().unwrap()) } #[de...
Rust
0
evision ) source_data.append({ 'SN': i, 'source_file': gerrit_source_filename, 'type': source_type, # 🆕 新增欄位 'name': proj['name'], ...
Python
1
# Code generated by Lark OpenAPI. import lark_oapi as lark from lark_oapi.api.corehr.v1 import * def main(): # 创建client client = lark.Client.builder() \ .app_id(lark.APP_ID) \ .app_secret(lark.APP_SECRET) \ .log_level(lark.LogLevel.DEBUG) \ .build() # 构造请求对象 request: ...
Python
1
_clip(text, audio_clip.duration) composite = CompositeVideoClip([ bg, end_clip.with_position(("center", "center")), text_clip.with_position(("center", 0.8), relative=True) ]).with_audio(a...
Python
1
on Client for %s", CONFIG.communication_services.endpoint ) return CallAutomationClient( # Deployment endpoint=CONFIG.communication_services.endpoint, # Performance transport=await azure_transport(), # Authentication credential=AzureKeyCredential( CON...
Python
1
icx.ptr -= 1; } } '+' => { icx.cells[icx.ptr] = icx.cells[icx.ptr].wrapping_add(1); } '-' => { icx.cells[icx.ptr] = icx.cells[icx.ptr].wrapping_sub(1); } '.' => { icx.stdout.write_all(&[icx.cells[icx.ptr]]).u...
Rust
0
:erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; #[native_implemented::function(maps:get/3)] pub fn result(process: &Process, key: Term, map: Term, default: Term) -> exception::Result<Term> { let boxed_map = term_try_into_map_or_badmap!(process, map)?; ...
Rust
0
LL: GLenum = 0x8037; pub const POLYGON_OFFSET_LINE: GLenum = 0x2A02; pub const POLYGON_OFFSET_POINT: GLenum = 0x2A01; pub const POLYGON_OFFSET_UNITS: GLenum = 0x2A00; pub const POLYGON_SMOOTH: GLenum = 0x0B41; pub const POLYGON_SMOOTH_HINT: GLenum = 0x0C53; pub const POLYGON_STIPPLE: GLenum = 0x...
Rust
0
ter() { match *item { syn::Item::Use(..) => { item.to_tokens(&mut tokens); }, syn::Item::Type(..) => { item.to_tokens(&mut tokens); }, syn::Item::Struct(ref struct_info) => { write_rental_struct_and_impls(&mut tokens, &struct_info); }, _ => panic!("Item must be a `use` or `struct`."),...
Rust
0
ge's root let curr_neighbor_root_idx = read_curr_neighbor_root_index(deps.storage, src_chain_id)?; save_curr_neighbor_root_index( deps.storage, src_chain_id, (curr_neighbor_root_idx + 1) % HISTORY_LENGTH, )?; save_neighbor_roots(deps.storage, (src_chain_id, curr_neighbor_root_id...
Rust
0
($($foo:literal),+) => { } } // @has decl_macro/macro.by_example_single.html //pre 'pub macro by_example_single($foo:expr) {' // @has - //pre '...' // @has - //pre '}' pub macro by_example_single { ($foo:expr) => {} } use multiinput::manager::{RawInputManager, DeviceType, XInputInclude,DeviceStats}; use m...
Rust
0
COLORS = { "bamboo_light": "#A8D8B9", "bamboo_medium": "#6BBF8E", "bamboo_dark": "#3A9D5A", "moss": "#8FBC8F", "forest": "#228B22", "background": "#A8D8B9", # bamboo_light "light_background": "#A8D8B9", # bamboo_light (ajusté pour cohérence) "dark_green": "#228B22", "backgrou...
Python
1
ch == '\u{200C}' || ch == '\u{200D}' || ch.is_mark_nonspacing() || ch.is_mark_spacing_combining() || ch.is_number_decimal_digit() || ch.is_punctuation_connector() } fn replace_invalid_middle_char(ch: char) -> char { if is_valid_middle_char(ch...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['connectivity.zip']) tmp_dir = tempfile...
Python
1
, types::{GetType, LhsValue, RhsValue, TypeMismatchError}, }; use serde::Serialize; #[derive(Debug, PartialEq, Eq, Clone, Serialize)] #[serde(tag = "kind", content = "value")] pub(crate) enum FunctionCallArgExpr<'s> { LhsFieldExpr(LhsFieldExpr<'s>), Literal(RhsValue), } impl<'s> FunctionCallArgExpr<'s> { ...
Rust
0