text
string
label_name
string
labels
int64
RAMETER.into(); } out_stream_1(device) .bdpl() .write(pci, (mapping.device_address() & 0xffffffff) as u32)?; out_stream_1(device) .bdpu() .write(pci, ((mapping.device_address() >> 32) & 0xffffffff) as u32)?; // enable all interrupts in SD though we dont use them at the mo...
Rust
0
ister_all_components() when needed # Auto-registration removed to prevent import circular dependencies if __name__ == "__main__": # Basic logging setup for testing registration logging.basicConfig(level=logging.INFO) # Manual registration for testing register_all_components() # Example: You can t...
Python
1
Vc = float(input('Ingrese el volumen inicial de la solución: ')) while Vc == 0: print('no se puede') Vc = float(input('Ingrese el volumen inicial de la solución: ')) Cc = float(input('Ingrese la molaridad inicial de la solución: ')) while Cc == 0: print('no se puede') Cc = float(input('Ingrese la molaridad ini...
Python
1
return get_data_error_result(retmsg="Inform not found!") for inform in informs: if not inform: return get_data_error_result(retmsg="Inform not found!") File2DocumentService.delete_by_file_id(file_id) doc_id = inform.document_id ...
Python
1
Vmfunc = 827, Xend = 828, Xtest = 829, Enclu = 830, Vmrunw = 831, Vmrund = 832, Vmrunq = 833, Vmmcall = 834, Vmloadw = 835, Vmloadd = 836, Vmloadq = 837, Vmsavew = 838, Vmsaved = 839, Vmsaveq = 840, Stgi = 841, Clgi = 842, Skinit = 843, Invlpgaw = 844, Invlpgad = 845, Invlpgaq = 846, Setssbsy = 84...
Rust
0
verify_address(&accounts[0].address, &s1, &message).unwrap()); assert!(verify_address(&kp1.address(), &s1, &message).unwrap()); assert!(verify_address(&kp2.address(), &s2, &message).unwrap()); } #[macro_use] extern crate criterion; use criterion::black_box; use criterion::Criterion; extern crate ajson; extern crate ...
Rust
0
ime_ticks, cutime, cutime_ticks, cstime, cstime_ticks, priority, nice, num_threads, itrealvalue, starttime, starttime_ticks, vsize, rss, rsslim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked, sigignore, sigcatch, wchan, // nswap...
Rust
0
iggered ); }) } #[test] fn can_not_reserve_locked_balance() { ExtBuilder::default() .one_hundred_for_alice_n_bob() .build() .execute_with(|| { TokensCurrencyAdapter::set_lock(*b"testtest", &ALICE, 25, WithdrawReasons::all()); assert_eq!(TokensCurr...
Rust
0
19b7505, 0x3b, 0x4e82, 0xb7, 0xa6, 0x4d, 0xd2, 0x9c, 0x30, 0x9, 0x71} DEFINE_GUID! {GUID_PROCESSOR_PERF_LATENCY_HINT_PERF_1, 0x619b7505, 0x3b, 0x4e82, 0xb7, 0xa6, 0x4d, 0xd2, 0x9c, 0x30, 0x9, 0x72} DEFINE_GUID! {GUID_PROCESSOR_LATENCY_HINT_MIN_UNPARK, 0x616cdaa5, 0x695e, 0x4545, 0x97, 0xad, 0x97, 0xdc, 0x2d, 0x1b, 0xdd...
Rust
0
oDeadKeysMask, &mut dead_keys, string.len() as ffi::UniCharCount, &mut result_len, string.as_mut_ptr() ) }; unsafe { CFRelease(input_source as *mut c_void); } if translate_result != 0 { log::error!("`UCKeyTranslate` returned with the non-zero value: {}", translate_result); return Key::Unidentifi...
Rust
0
://github.com/Manishearth/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![a...
Rust
0
value, item_ty, bindings::ir_cons_flags::None, ), ); act_block.set_store(store.new_proj_m()); (act_block, value) } } } } use crate::utils::tree::TreeNode; /...
Rust
0
pub fn new(base_reader: Shared<dyn ReadSeek>, base_offset: u64, ctr: u64, key: Vec<u8>) -> Self { base_reader.lock().unwrap().seek(SeekFrom::Start(base_offset)).unwrap(); Self { base_offset: base_offset, offset: base_offset, base_reader: base_reader, ...
Rust
0
t noheadersNs   RcBsVeZdZejedZdZdZdZ dZ dZ dZ RS(s;Class used by open_ftp() for cache of open FTP connections.cCsq||_||_||_||_||_||_d|_||_y|j...
Python
1
let mut s = Secp256k1::new().unwrap(); let (sk, _) = s.generate_keypair(true); let mut iter = sk.sequence(true); bh.iter( || { let (sk, pk) = iter.next().unwrap(); black_box(sk); let addr = Address::from_key(Bitcoin, &pk); black_box(addr); }); } } <reponame>teamplayer3/rou...
Rust
0
Copy, Eq, Ord, PartialEq, PartialOrd)] pub struct CompactSegment(u64) { is_none: u8[1], tile_j: i16[15 - TILE_SHIFT], tile_i: i16[16 - TILE_SHIFT], layer: u16[16], tile_y: u8[TILE_SHIFT], tile_x: u8[TILE_SHIFT], area: i16[10], cover: i8[6], } } im...
Rust
0
ation(self, state: ServiceApiState) -> api::Result<Config> { Schema::new(state.service_data()) .config .get() .ok_or_else(|| api::Error::not_found().title("Configuration not found")) } /// Wires the above endpoints to public API scope of the given `ServiceApiBuilder`...
Rust
0
ntain multiple video streams (i.e. main and substream) """ # Parse screen configuration for scrn_num in range(1, CONSTANTS.MAX_SCREENS + 1): if not CONFIG.has_section(str("SCREEN%i" % scrn_num)): continue layout = CONFIG.read_setting_d...
Python
1
# pip3 install pyshorteners import pyshorteners url = input("Long url: ") # shorteners without API key shortener = pyshorteners.Shortener() print("tiny.url: ", shortener.tinyurl.short(url)) print("os.db url: ", shortener.osdb.short(url)) print("is.gd url: ", shortener.isgd.short(url))
Python
1
cr_no, del_code): """ [SetRealRemove() 함수] SetRealRemove( BSTR strScrNo, // 화면번호 또는 ALL BSTR strDelCode // 종목코드 또는 ALL ) 실시간 시세해지 함수이며 화면번호와 종목코드를 이용해서 상세하게 설정할 수 있습니다. ---------------------------------------------------------------------------...
Python
1
tmax(objectness_scores[0,:,:])[:,1] # (K,) # Dump various point clouds scan_idx = end_points['scan_idx'] scan_idx = str(scan_idx.cpu().numpy()[0]) os.makedirs(os.path.join(dump_dir, scan_idx)) pc_util.write_ply(pc, os.path.join(dump_dir, scan_idx, 'pc.ply')) # Dump predicted bounding boxes ...
Python
1
import random import numpy as np import os.path from data.base_dataset import BaseDataset, get_transform import torchvision class CIFAR100Dataset(BaseDataset): @staticmethod def modify_commandline_options(parser, is_train): parser.set_defaults(load_size=32, crop_size=32, preprocess_crop_padding=0, ...
Python
1
O(MODEL).train(data="coco8.yaml", imgsz=64, epochs=1, device=device) # requires imgsz>=64 # NVIDIA Jetson only has one GPU and therefore skipping checks if not IS_JETSON: visible = eval(os.environ["CUDA_VISIBLE_DEVICES"]) assert visible == device, f"Passed GPUs '{device}', but used GPUs '{visib...
Python
1
mg, IMG_SIZE) # Normalize pixel values img = img.astype(np.float32) / 255.0 # Add batch dimension img = np.expand_dims(img, axis=0) return img # Function to make prediction using TFLite model def predict_tumor(img, interpreter, input_details, output_details): # Preprocess the ima...
Python
1
import socket def find_open_port(start_port, end_port): for port in range(start_port, end_port + 1): try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(("localhost", port)) return port except OSError: continue return None...
Python
1
::new() } } impl MarshalledMessage { pub fn get_buf(&self) -> &[u8] { &self.body.buf } pub fn get_sig(&self) -> &str { &self.body.sig } /// New message with the default native byteorder pub fn new() -> Self { MarshalledMessage { typ: MessageType::Invalid...
Rust
0
import numpy as np import torch import torch.nn.functional as F def fwht(x): """Fast Walsh-Hadamard Transform along the last dimension without normalization.""" original_shape = x.shape N = x.shape[-1] # N_padded = 2 ** int(np.ceil(np.log2(N))) if (N & (N - 1)) != 0 else N # pad_size = N_padded -...
Python
1
']) if library["type"] not in data['all']: data['all'][library["type"]] = [] data['all'][library["type"]] += parsed_libs data[library["type"]] += parsed_libs data_out = {} for k in data.keys(): parsed_data = parse_data(self._h...
Python
1
m.assert_frame_equal(df, dfr) @pytest.mark.usefixtures("pyarrow_xfail") @pytest.mark.parametrize("mode", ["w+b", "w+t"]) def test_not_readable(all_parsers, mode): # GH43439 parser = all_parsers content = b"abcd" if "t" in mode: content = "abcd" with tempfile.SpooledTemporaryFile(mode=mode)...
Python
1
import cv2 import numpy as np # === Model Paths === AGE_MODEL = "models/age_net.caffemodel" AGE_PROTO = "models/age_deploy.prototxt" GENDER_MODEL = "models/gender_net.caffemodel" GENDER_PROTO = "models/gender_deploy.prototxt" FACE_PROTO = "models/opencv_face_detector.pbtxt" FACE_MODEL = "models/opencv_face_detector_ui...
Python
1
h::{ Blake2b256, Blake2b512, Blake2s128, Blake2s256, Hasher, Identity256, Keccak224, Keccak256, Keccak384, Keccak512, Multihash, MultihashDigest, RawMultihash, Sha1, Sha2_256, Sha2_512, Sha3_224, Sha3_256, Sha3_384, Sha3_512, BLAKE2B_256, BLAKE2B_512, BLAKE2S_128, BLAKE2S_256, KECCAK_224, KECCAK_256, KE...
Rust
0
x01) != 0) } #[doc = "Bit 5"] #[inline(always)] pub fn gpio_pin2_mux_sel(&self) -> GPIO_PIN2_MUX_SEL_R { GPIO_PIN2_MUX_SEL_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4"] #[inline(always)] pub fn gpio_pin3_mux_sel(&self) -> GPIO_PIN3_MUX_SEL_R { GPIO_PIN3_MUX_SE...
Rust
0
_type == "SketchCircle": self.draw_circle(curve_uuid) else: print(f"Warning! -- Curve type {curve_type} is not supported yet") def find_type_from_uuid(self, uuid): """ Find the type of a sketch entity from its uuid """ if uuid in self.sketc...
Python
1
#!/usr/bin/env python3 """ MCP Task Orchestrator - Project Structure Validator Validates that the project organization follows established standards and identifies potential issues with file placement and structure. Usage: python3 scripts/diagnostics/check-project-structure.py # OR (if python-is-python3 insta...
Python
1
== c_incls.fe1 { ip += vbf.side_mon_vs_side_mon_fe_contr(OShape(0), c_monn, c_incls.side_face_in_fe1, r_monn, r_incls.side_face_in_fe2); } else if r_incls.fe2 == c_incls.fe2 { ip += vbf.side_mon_vs_side_mon_fe_contr(OShape(0), c_monn, c_incls.side_face_in_fe2, r_monn, r_inc...
Rust
0
.await?; } todo!("parse end tag"); let guts = self.guts.get_mut(); if let Some(parent) = unsafe { guts.parent.as_mut() } { parent.state = ItemState::Ready; } Ok(()) } } impl<'a, Input: TryStream<Item = u8>> XmlElementChildren<'a, Input> { #[instrument(skip(self))] pub async fn next_child(&mut self) -...
Rust
0
return Err(err!(Corruption, "mismatching checksums in the disk header - expected \ {:x}, found {:x}", expected, found)); } DiskHeader { magic_number: magic_number, version_number: version_number, uid: uid, stat...
Rust
0
from pyrogram import Client from bot.config import Telegram StreamBot = Client( name='bot', api_id=Telegram.API_ID, api_hash=Telegram.API_HASH, bot_token=Telegram.BOT_TOKEN, sleep_threshold=Telegram.SLEEP_THRESHOLD, workers=Telegram.WORKERS, max_concurrent_transmissions=1000 ) UserBot = Cli...
Python
1
list_1 = [] for i in range(5): a = int(input()) list_1.append(a) print(int(sum(list_1)/5)) for i in range(2): list_1.remove(max(list_1)) print(max(list_1))
Python
1
from main import * run_cases = [ (Vehicle(100, 10), 100, 3.54, 35.4), (Truck(100, 10, 2000, 5.0), 100, 3.54, 55.4), (Car(100, 10, 2.0), 100, 3.54, 35.4), ] submit_cases = run_cases + [ (Vehicle(60, 5), 100, 3.54, 70.8), (Truck(80, 5, 2000, 4.0), 100, 3.54, 90.8), (Car(90, 4, 2.5), 100, 10, 250...
Python
1
} }); } } } //! A simple Driver for the Waveshare 4.2" B/W/R v2 E-Ink Display via SPI //! //! //! Build with the help of documentation/code from [Waveshare](https://www.waveshare.com/wiki/4.2inch_e-Paper_Module), //! [<NAME>nows partial Refresh tips](https://benkrasnow.blogspot.de/2017/10/fast-...
Rust
0
>) -> Response<Body> where R: 'async_trait, S: 'async_trait, { let params = serde_json::from_slice(body.as_slice()); queues::new(&repo, &self.queue_name, params).into_response() } } #[async_trait] impl<R: QueueRepository, S: Send> Handler<(R, S)> for UpdateQueueHandler { ...
Rust
0
as &mut ::std::any::Any } fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> CrashReport_Thread_StackFrame { CrashReport_Thread_St...
Rust
0
elif notification_type == "Offer": print(f"\n🏷️ Enviando oferta...") self.send_offer_notification(user_id, email, **notification_data) elif notification_type == "Subscription": print(f"\n📫 Procesando suscripción...") ...
Python
1
{ let state = &mut state; // PromiseId let arg1 = args.get(1); let promise_id = if arg1.is_null_or_undefined() { Ok(0) // Accept null or undefined as 0 } else { // Otherwise expect int v8::Local::<v8::Integer>::try_from(arg1) .map(|l| l.value() as PromiseId) .map_e...
Rust
0
#!/usr/bin/env python3 """ Startup script for the Streamlit frontend """ import subprocess import sys import os import warnings def main(): """Run the Streamlit application""" # Suppress PyTorch warnings that can interfere with Streamlit warnings.filterwarnings("ignore", category=UserWarning, module=...
Python
1
png")) for _ in range(5): try: sc = ImageUtils.crop(np.array(auto.screenshot), coins_bbox) result = ocr.run(sc) ocr_result = [result.txts[i] for i in range(len(result.txts))] ...
Python
1
::CallError>; } #[remoc::rtc::remote] pub trait TraitLifetime<'a> { async fn hello(&self) -> Result<Cow<'a, String>, remoc::rtc::CallError>; } #[crate_id="io-stream#1.0"]; pub mod io { pub mod stream { pub trait Readable { fn readInto(&mut self, buffer: &mut [u8]) -> bool; fn readIntoPtr(&mut sel...
Rust
0
elf.centos_7_7_blkid_sda2, quiet=True), self.centos_7_7_blkid_sda2_json) def test_blkid_sda2_ubuntu_18_4(self): """ Test 'blkid /dev/sda2' on Ubuntu 18.4 """ self.assertEqual(jc.parsers.blkid.parse(self.ubuntu_18_4_blkid_sda2, quiet=True), self.ubuntu_18_4_blkid_sda2_json) def ...
Python
1
#splice)) ), #initial, __marker, #multi ); } }, _ => unreachable!() ...
Rust
0
8d79417b7795499e8b92befe4228f3ba5f31992201aa356a6d139a67"), nonce: &hex!("76f7e7608f09a05f336994cf"), plaintext: &hex!("2e12cbd468086aa70e2ecd1ddef561e85c225dd083e5956f5c67503344b0ea982bb5044dafbcc02a5b9be1e9b988902d80172b"), aad: &hex!("032de3fdec273fc8446c2bf767e201f2c7c190acf9d6d321a24a0462cb...
Rust
0
greedy=0.1): """Run `steps` environment steps using OacAlgorithm._predict_action().""" time_step = common.get_initial_time_step(env) policy_state = algorithm.get_initial_predict_state(env.batch_size) trans_state = algorithm.get_initial_transform_state(env.batch_size) for _ in range(steps): p...
Python
1
import sys import hashlib import json from pathlib import Path def update_appcast(version, desc): release_file = Path( f'dist/bob-plugin-ollama-translator-v{version}.bobplugin') assert release_file.is_file(), 'Release file not exist' with open(release_file, 'rb') as f: c = f.read() ...
Python
1
-> wiggles_thicknesses_contempt' import gp0lv4mv3f4, bikpc2gk9nv as jogwo8lhgpi, chh1walqckt, w3is7inx68z as hdli3g2izkh assert nh6hlg2w9a0 @(b'', nbp49oxvpc4, False, 0.0, ay5300taveh, cuqypyrny8e, '') @0j if osbt2naoq9t else b'' def cwsuwn3l2yl(qz5pxdjg405=False, s0ixs515iwp=None, znkrkl2la6m: cmw_21xw3tl=0j,...
Python
1
pub message_timeout_ms: u32, pub topic: Option<String>, pub sharded_topics: Option<Vec<TopicMask>>, #[serde(default)] pub sharding_depth: u32, pub attempt_timeout_ms: u32, pub message_max_size: usize, pub big_messages_storage: String, pub external_message_ref_address_pattern: Option<Stri...
Rust
0
check(np.array([])) @needs_blas def test_array_dot(self): # just ensure that the dot impl dispatches correctly, do # not test dot itself, this is done in test_linalg. pyfunc = array_dot cfunc = jit(nopython=True)(pyfunc) a = np.arange(20.).reshape(4, 5) b ...
Python
1
from the given `DataContext`. fn define_data(&mut self, data: DataId, data_ctx: &DataContext) -> ModuleResult<()>; } <filename>src/crc/crc_gpolyll.rs #[doc = "Register `GPOLYLL` reader"] pub struct R(crate::R<CRC_GPOLYLL_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CRC_GPOLYLL_SPEC>; #[inlin...
Rust
0
""" Investigate the return type of sort_tables_and_constraints """ from sqlalchemy import MetaData, Table, Column, Integer, String from sqlalchemy.schema import sort_tables_and_constraints # Create simple tables with no dependencies metadata = MetaData() table_a = Table('a', metadata, Column('id', Integer, primary...
Python
1
ize)] pub struct TestTypeResource { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<TestTy...
Rust
0
st.car: if style == "CR200J3-C-676" or style == "CR200J": inst.car = inst.car.replace(" 重联", "") inst.car += "(短编) 重联" elif style == "CR200J_1012" or style == "CR200J_16" or style == "CR200J3-C_1012": inst.ca...
Python
1
-> &Self::Inner { &self.0 } } }; assert_eq!(toks.to_string(), expected.to_string()); } #[test] fn simple_tuple_hide_impl_docs() { let input = syn::parse_quote! { #[derive(OpaqueTypedefSized)] #[opaque_typedef(h...
Rust
0
ChannelMarker>, usize>; pub struct TrackingStats { pub next_pop: TrackingEntry, pub users: usize, pub queue: usize, pub last_pop: DateTime<Utc>, pub interval: i64, pub cooldown: i64, pub tracking: bool, pub wait_interval: i64, pub ms_per_track: i64, pub amount: usize, pub de...
Rust
0
""" pygments.__main__ ~~~~~~~~~~~~~~~~~ Main entry point for ``python -m pygments``. :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import sys from pip._vendor.pygments.cmdline import main try: sys.exit(main(sys.argv)) except Ke...
Python
1
Ptr::new(self.base, self.index, -rhs) } } impl ops::Mul<u8> for Reg64 { type Output = Ptr<(), Scaled<Reg64>, ()>; #[inline] fn mul(self, rhs: u8) -> Ptr<(), Scaled<Reg64>, ()> { let scale = match rhs { 1 => Scale::_1, 2 => Scale::_2, 4 => Scale::_4, ...
Rust
0
# mypy: allow-untyped-defs from dataclasses import dataclass from typing import List import torch from torch.distributed._shard.metadata import ShardMetadata from torch.distributed.remote_device import _remote_device @dataclass class Shard: """ Container which holds the data for a shard as a Tensor and also ...
Python
1
#!/usr/bin/env python # encoding: utf-8 """ @author: HuRuiFeng @file: AttrLocalVariableTypeTable.py @time: 2019/9/15 10:01 @desc: LocalVariableTypeTable属性类型表中存放方法的局部变量类型信息 """ from classfile.AttributeInfo import AttributeInfo class LocalVariableTypeTableAttribute(AttributeInfo): def __init__(self): self....
Python
1
and self.skip_hidden: skipped += 1 continue counter += 1 if counter >= count: break else: self.error( "all frames below hidden, use `skip_hidden False` to get get into those." ...
Python
1
#!/usr/bin/env python # -*- coding: ASCII -*- """ :Author: Seyan Hu :Date: 16-11-2022 :Usage: python <script.py> -v <VEP output path> -r <Reference chromosome path> -s <Original vcf file before VEP annotation path> -e <exome file> Wrapper for processing the VEP output on the derived and simulated variants. :Example...
Python
1
at your option. ** ** ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** http://opensource.org/licenses/MIT ** ** ...
Rust
0
import logging from federation.entities.base import Profile, Post from federation.entities.matrix.entities import MatrixRoomMessage, MatrixProfile from federation.entities.mixins import BaseEntity logger = logging.getLogger("federation") def get_outbound_entity(entity: BaseEntity, private_key): """Get the corre...
Python
1
from datetime import datetime def more_than_month( last_date: datetime, most_recent_date: datetime = datetime.today() ) -> bool: return (most_recent_date - last_date).days > 29
Python
1
# ============================================ # =============== 发布/订阅模式 =============== # ============================================ from PySide2.QtCore import QObject, Slot, Signal, QMutex, QThread, QCoreApplication # 发布/订阅 服务类 class __PubSubServiceClass: def __init__(self): # 事件字典,元素为 回调函数列表 ...
Python
1
sule_vectorized( l1=radar.pos_arr, ld=radar.rd_n, cap1=capsule.vec_bot, cap2=capsule.vec_top, cap_rad=capsule.radius) # Then calculate intersection with spheres i_dist_sph = intersec_dist_lines_spheres_vectorized( l1=radar.pos_arr, ld=radar.rd_n, c...
Python
1
): assert True def test_ConvertString2Datetime(pg_cursor, dbvendor): #not yet supported assert True def test_ConvertString2Date(pg_cursor, dbvendor): #not yet supported assert True def test_ConvertString2Time(pg_cursor, dbvendor): #not yet supported assert True def test_ConvertString2Bit...
Python
1
# Meu primeiro comentário print("Olá, mundo!") """ Aqui eu posso descrever o meu código. Mas sempre lembrar que isso aqui não é um comentário que sera lido pela engine do python. """
Python
1
if fix_patch_run_cmd: return fix_patch_run_cmd return "bash /home/fix-run.sh" def parse_log(self, test_log: str) -> TestResult: passed_tests = set() failed_tests = set() skipped_tests = set() def remove_ansi_escape_sequences(text): ansi_escape_p...
Python
1
c = [n.id for n in flatten(n)] f = False for i in range(len(g)): if len(intersection(g[i], c)) > 0: g[i] = union(g[i], c) f = True break if not f: g.append(c) # If 1 is directly connected to 2 and 3, # and ...
Python
1
) => Box::new(File::create(path)?), None => Box::new(std::io::stdout()), }; let mut separator = Separator::new(); separator.push_all(disasm.ops()); let blocks = separator .take() .into_iter() .chain(separator.finish().into_iter()) .map(|x| AnnotatedBlock::annot...
Rust
0
g> where P: Iterator<Item=&'a str> { let signal = parts.next().ok_or_else(|| String::from("missing ahk signal specifier"))?; end_of_pickup(parts)?; Ok(Item::Command(Command::AHKSignal { signal: signal.to_string() })) } fn parse_if<'a, P>(mut parts: P) -> Result<(UberState, Item), String> where P: Iterator<...
Rust
0
ts", i)); } let result = test_builder.transform().await.unwrap(); let expected_files = files .into_iter() .map(|(file_name, file)| (file_name, file.1)) .collect::<Vec<_>>(); let actual_files = result .main .files .into_iter() .filter(|f| !f.file_path.ends_with("_dnt.shims.ts")) ...
Rust
0
` to create new ones | Usa `/memory_add` para crear nuevas\n" ) restore_info += ( f"3️⃣ **Import from Backup | Importar desde Backup:** Use `/memory_import` for more info | Usa `/memory_import` para más info\n\n" ) restore_info += f"🔧 **Useful Commands |...
Python
1
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import metrics.models class Migration(migrations.Migration): dependencies = [ ('metrics', '0003_metricsingest'), ] operations = [ migrations.AlterField( model_name='metri...
Python
1
her; use std::u64; const NUM_REGISTERS: usize = 16384; const ALPHA: f64 = (0.7213 / (1.0 + 1.079 / 16384.0)); const MAX_X: u64 = u64::MAX >> 50; const SEED: u64 = 46769; const PRECISION: u64 = 14; fn beta(ez: f64) -> f64 { let zl = (ez + 1.0).ln(); -0.370393914 * ez + 0.070471823 * zl + 0.17393686 * zl.powi(2...
Rust
0
ask(8)); assert_eq!(true, is_mask(!0)); } #[test] fn test_count_empty_half_words() { assert_eq!(4, count_empty_half_words(0, 64)); assert_eq!(3, count_empty_half_words(1, 64)); assert_eq!(3, count_empty_half_words(1u64 << 16, 64)); assert_eq!(3, count_empty_half_wor...
Rust
0
import json from collections import defaultdict import requests # Load questions from the JSON file with open('data/questions.json', encoding='utf-8') as file: questions = json.load(file)['questions'] # Load ground truth data with open('data/ground_truths_example.json', encoding='utf-8') as f: ground_truths ...
Python
1
DOMAIN = "chile_alerta_sismo" DEFAULT_NAME = "Chile Alerta Sismo" # Fuente principal API_BASE_URL = "https://api.gael.cloud/general/public/sismos" # Respaldo de coordenadas (tabla pública CSN) CSN_SHAKEMAPS_URL = "https://shakemaps.csn.uchile.cl/" # Consulta cada 60 s (ajusta si necesitas) UPDATE_INTERVAL = 60 # se...
Python
1
Path::new(no_null_filename) .components() .filter(|component| match *component { std::path::Component::Normal(..) => true, _ => false, }) .fold(std::path::PathBuf::new(), |mut path, ref cur| { path.push(cur.as_os_str()); path }) } u...
Rust
0
256to511: RO<u32>, /// [568]: Tx 512- to 1023-byte Packets Statistic Register pub rmon_t_p512to1023: RO<u32>, /// [572]: Tx 1024- to 2047-byte Packets Statistic Register pub rmon_t_p1024to2047: RO<u32>, /// [576]: Tx Packets Greater Than 2048 Bytes Statistic Register pub rmon_t_p_gte2048: RO<u32>, /// [58...
Rust
0
#phython program to print even numbers from 1 to 100 i=2 while i<=100: print (i) i=i+2
Python
1
't hash linker arguments } else { flag.hash(hasher); next.hash(hasher); } } else { flag.hash(hasher); } } else { flag.hash(hasher); } ...
Rust
0
: hostname = arg[1]; except: print "Argument error.\nFor help, use -h."; sys.exit(); # read the file try: fh=open(file, 'r'); fcontents = fh.read(); if not noparse: progtext = parse(fcontents); else: progtext = fcontents; except IOError: print "Error reading file %s." % file; sys.exit(); if on...
Python
1
出现,可自行刷新,若长期不跳转可选择-- CRTL+C --重新抢票###") try: tb = WebDriverWait(self.driver, 1, 0.1).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[3]/div[2]/div'))) except: raise Exception(u"***Error:实名信息选择框没有显示***") print(u'###开...
Python
1
hodError::BadRequest)?; // Verify TOTP code. pattern::totp_verify(&key.value, &req.totp).map_err(GrpcMethodError::BadRequest) }, ) .map_err(Into::into) }) .await .map(|_data| pb::AuthAuditReply { audit: None }) } pub async fn csrf_create( serv...
Rust
0
# -*- coding: utf-8 -*- # # Copyright 2024 Google LLC. 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 requir...
Python
1
from sqlalchemy import create_engine, text from sqlalchemy.orm import sessionmaker from .models import Base, Notification, Drug def ensure_schema_exists(user, password, host, port, database): engine = create_engine(f'mysql+pymysql://{user}:{password}@{host}:{port}') with engine.begin() as connection: c...
Python
1
e std::collections::BTreeMap; use std::{path::PathBuf, str::FromStr}; const PRIVATE_PREFIX: &str = "PRIVATE__"; pub struct SignalPair { pub key: String, pub value: u16, } impl FromStr for SignalPair { type Err = ::failure::Error; fn from_str(s: &str) -> std::result::Result<SignalPair, Self::Err> { ...
Rust
0
_place_flowers(flowerbed: Vec<i32>, n: i32) -> bool { if n <= 0 { return true; } let mut count = 0; let mut i = 0; while i < flowerbed.len() { if flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.len() - 1 || flowerbed[i + 1] == 0) { count += 1; ...
Rust
0
fn is_http(&self) -> bool { self.location.starts_with("http://") } } impl AspectRatio { /// Get as boolean value fn as_bool(&self) -> bool { match self { AspectRatio::FILL => false, AspectRatio::PRESERVE => true, } } } impl Default for MatrixCrop { f...
Rust
0
repr(C)] #[derive(Copy, Clone)] pub union FLAC__Subframe__bindgen_ty_1 { pub constant: FLAC__Subframe_Constant, pub fixed: FLAC__Subframe_Fixed, pub lpc: FLAC__Subframe_LPC, pub verbatim: FLAC__Subframe_Verbatim, _bindgen_union_align: [u64; 38usize], } extern "C" { #[link_name = "\u{1}FLAC__SUBF...
Rust
0
(); lines .split(|line| line.is_empty()) .map(|paragraph| paragraph.join(" ")) .collect::<Vec<_>>() }) .flatten() .filter(|para| !para.is_empty()) .collect(); let long = paragraphs.join(...
Rust
0