text
string
label_name
string
labels
int64
eq!(cpu.get_status("D"), true); //Interrupt set. cpu.set_status(2, false); cpu.SEI(); assert_eq!(cpu.get_status("I"), true); } #[test] fn testOP_LDA(){ let mut cpu = super::CPU::new_empty(); cpu.memory.set(0x755, 234); // Random positi...
Rust
0
function at /// that point. fn eval(key: &Self::Key, point: &Self::Domain) -> Result<Self::Share, Box<dyn Error>>; /// Takes the secret shares as input, and outputs the corresponding function value. fn decode(shares: (&Self::Share, &Self::Share)) -> Result<Self::Range, Box<dyn Error>>; } /// Helper f...
Rust
0
from __future__ import absolute_import import ROOT from .. import compiled as C __all__ = [ 'close_on_esc_or_middlemouse', 'attach_event_handler', ] C.register_code(""" #include <TPython.h> #include <TPyDispatcher.h> class TPyDispatcherProcessedEvent : public TPyDispatcher { public: TPyDispatcherProces...
Python
1
model) return value def field_names(self, admin_model): """Returns the names of the fields/columns used by the given admin model. :param admin_model: Instance of a :class:`admin.ModelAdmin` object that is responsible for displaying the change list :r...
Python
1
from utils.text.text_encoder import is_sil_phoneme REGISTERED_TEXT_PROCESSORS = {} def register_txt_processors(name): def _f(cls): REGISTERED_TEXT_PROCESSORS[name] = cls return cls return _f def get_txt_processor_cls(name): return REGISTERED_TEXT_PROCESSORS.get(name, None) class Base...
Python
1
d def is_pooling_model(model: object) -> TypeIs[AphroditeModelForPooling]: ... def is_pooling_model( model: Union[type[object], object], ) -> Union[TypeIs[type[AphroditeModelForPooling]], TypeIs[AphroditeModelForPooling]]: if not is_aphrodite_model(model): return False return getattr(model, "...
Python
1
from django.db import models from django.conf import settings from django.core.validators import MinValueValidator from decimal import Decimal import uuid from django.utils import timezone from users.models import UserProfile import qrcode from io import BytesIO from django.core.files.base import ContentFile from phar...
Python
1
.get(15).is_none()); // but not in place position // bv[12] = false; // because it cannot produce `&mut bool`. // instead, use `.get_mut()`: *bv.get_mut(12).unwrap() = false; // or `.set()`: bv.set(12, false); // range indexing produces subslices let last = &bv[12..]; assert_eq...
Rust
0
mut merge_branes_2 = dump(&c); check_brane_cones( &merge_branes_2, &[(&b""[..], &b"k1"[..]), (b"k1", b"k4"), (b"k4", b"")], ); // Add peer let (brane1, role1) = merge_branes_2.remove(1); assert_eq!(role1, StateRole::Leader); assert_eq!(brane1.get_peers().len(), 1); assert_eq...
Rust
0
# phonebook = { # "John":"07069780275", # "Miracle":"07045897654", # "Albert":"08064142148" # } # print(phonebook["John"]) # phonebook.pop("John") # print(phonebook) phonebook = {} phonebook['John'] = '080' phonebook['favour'] = '070' phonebook['miracle'] = '091' print(phonebook) print(phonebook['favour'...
Python
1
op': { 'prefix_or_id': { 'SR Adj (idx 0)': { 'outgoing_interface': { 'GigabitEthernet0/0/0/1': { 'bytes_switched': 0, 'next_hop': '10.3.4.4', ...
Python
1
(&entry, hash).await } pub async fn paused_transactions_iter( &self, hash: ::core::option::Option<T::Hash>, ) -> ::core::result::Result< ::subxt::KeyIter<'a, T, PausedTransactions>, ::subxt::Error, > { self.client.storage().iter(hash).await } } } } pub mod runtime_typ...
Rust
0
_SPEC>`"] pub type SYST_CALIB = crate::Reg<syst_calib::SYST_CALIB_SPEC>; #[doc = "SysTick Calibration Value Register r"] pub mod syst_calib; #[doc = "NVIC_ISER0 register accessor: an alias for `Reg<NVIC_ISER0_SPEC>`"] pub type NVIC_ISER0 = crate::Reg<nvic_iser0::NVIC_ISER0_SPEC>; #[doc = "Interrupt Set-enable Register ...
Rust
0
from .base import Attack from .apgd import LinfAPGDAttack from .apgd import L2APGDAttack from .fgsm import FGMAttack from .fgsm import FGSMAttack from .fgsm import L2FastGradientAttack from .fgsm import LinfFastGradientAttack from .pgd import PGDAttack from .pgd import L2PGDAttack from .pgd import LinfPGDAttack fro...
Python
1
# Copyright Amazon.com, Inc. or its affiliates. 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 # # Unl...
Python
1
iption_id: SubscriptionID, }, /// /// [Unsubscribe Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#unsubscribe) /// Unsubscribe { #[serde(rename = "requestId")] request_id: ReqID, error: ActionError, timestamp: u128, #[serde...
Rust
0
# main.py from gemini_assistant import GeminiAssistant def add_numbers(a: float, b: float) -> float: """Adds two numbers together.""" print(f"TOOL_USED: Adding {a} and {b}") return a + b def subtract_numbers(a: float, b: float) -> float: """Subtracts one number from another.""" print(f"TOOL_USED: ...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 18 17:24:37 2024 @author: Erenulug """ import pandas as pd from rdkit import Chem from rdkit.Chem import BRICS import types import re import logging def read_smiles_from_excel(file_path): df = pd.read_excel(file_path) df = df[df['SMILES']....
Python
1
enter_editmode=False, calc_uvs=True) bpy.ops.object.mode_set(mode = 'EDIT') bpy.ops.mesh.faces_shade_smooth() set_generic(entity, False) return bpy.context.active_object def add_sphere(entity): bpy.ops.mesh.primitive_cube_add(location=(0,0,0), enter_editmode=False, calc_uvs=True) ...
Python
1
# MIT licensed # Copyright (c) 2013-2020 lilydjwg <lilydjwg@gmail.com>, et al. import re from nvchecker.api import session, GetVersionError async def get_version(name, conf, *, cache, **kwargs): try: regex = re.compile(conf['regex']) except re.error as e: raise GetVersionError('bad regex', exc_info=e) ...
Python
1
:render($p)?; crate::NcPlane::rasterize($p)?; sleep![$( $sleep_args ),+]; }; ($nc:expr, $( $sleep_args:expr),+ ,) => { rsleep![$nc, $( $sleep_args ),* ] }; } /// [`NcDirect.flush`][NcDirect#method.flush]\(`$ncd`\)? + [`sleep!`]`[$sleep_args]`. /// /// Flushes the `$ncd` [NcDirect] o...
Rust
0
import logging import queue import subprocess import time from collections import deque from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED from DMR.utils import ToolsList class StreamlinkSyncDownloader(): def __init__(self, segment:int, url:str, ...
Python
1
import numpy as np import scipy.signal def makekernel(size: int) -> np.ndarray: assert size % 2 == 1 kernel_vect = scipy.signal.windows.gaussian(size, std=size / 6.0, sym=True) kernel = np.outer(kernel_vect, kernel_vect) kernel = kernel / kernel.sum() return kernel def create_cloud_mask(classifi...
Python
1
rn the relative error instead of the absolute error Returns: float: Maximum absolute difference between reference and test gradients """ # Forward pass ref_output = ref_fn(**ref_inputs) test_output = fn(**test_inputs) # Backward pass with same gradient grad = torch.ones_like(ref...
Python
1
""" Benchmarking utilities for fast inference. """ from .benchmarking import benchmark_inference, compare_methods __all__ = ["benchmark_inference", "compare_methods"]
Python
1
let inf = f32::INFINITY; let max = u32::MAX; // Same shape assert_eq!(a.debug_abs_all_tol(&b, &0.2), Some(map12(0.2, 0.2))); assert_eq!(a.debug_rel_all_tol(&b, &0.2), Some(map12(0.5, 0.85))); assert_eq!(a.debug_rmax_all_tol...
Rust
0
str { "in" } fn atword(&self) -> &'static str { "in" } fn everystr(&self) -> &'static str { "" } } impl FieldDisp for DayOfWeek { fn typestr(&self) -> &'static str { "day-of-week" } fn atstr(&self) -> &'static str { "on" } fn atword(&self) -> &'static str { "on" } fn everystr(&self) -> &'...
Rust
0
}; // In the absence of callback attributes this is a regular argument. let mut bindgen_ty = BindgenArgType::Regular; // In the absence of serialization attributes this is a JSON serialization. let mut serializer_ty = SerializerType::JSON; for attr in &mut original.attrs { ...
Rust
0
> { use xz2::read::XzDecoder as Decoder; let mut decoder = Decoder::new(data); let mut decompressed = Vec::new(); decoder.read_to_end(&mut decompressed)?; decompressed } // Some(b"sNaPpY") => { Some(&[0xf...
Rust
0
et() # self.val_metrics_positive.reset() # self.val_metrics_negative.reset() # if self.test_every_metrics is not None: # self.log_dict(self.test_every_metrics.compute(), on_step=False, on_epoch=True) # self.test_every_metrics.reset() print("intermediate result:", ...
Python
1
# Detector used for the environment with rectangles based on real websites (Section 4.16) from wed.utils.bounding_box import BoundingBox, BoundingBoxType, RectI from cv2.typing import MatLike import cv2 def draw_rect(bb: RectI, image: MatLike) -> None: """Draws a rectangle in the image Args: bb (Rect...
Python
1
p!(Str32, Box<Str32>); impl_cmp!(&'a Str32, String); impl_cmp!(&'a Str32, str); impl_cmp!(&'a Str32, Cow<'b, Str32>); impl_cmp!(&'a Str32, Cow<'b, str>); impl_cmp!(&'a Str32, Box<str>); impl_cmp!(&'a Str32, Box<Str32>); impl TryFrom<String> for String32 { type Error = TryFromStringError<String>; fn try_from(s...
Rust
0
# Copyright (c) OpenMMLab. All rights reserved. from argparse import ArgumentParser from mmdet3d.apis import (inference_mono_3d_detector, init_model, show_result_meshlab) def main(): parser = ArgumentParser() parser.add_argument('image', help='image file') parser.add_argument('a...
Python
1
u32> = vec![]; for slope_to_consider in slopes_to_consider.iter() { encountered_trees.push(traverse_slope( &full_forest, slope_to_consider[0], slope_to_consider[1], )); } println!( "PART 2: Encountered trees : {:?}", encountered_...
Rust
0
def f(s, n): ls = s.rsplit() out = [] while len(ls) >= n: out += ls[-n:] ls = ls[:-n] return ls + ['_'.join(out)]
Python
1
# Change priority of sub-meshes in Mesh from salome.kernel import salome salome.salome_init_without_session() from salome.geom import geomBuilder from salome.smesh import smeshBuilder geom_builder = geomBuilder.New() smesh_builder = smeshBuilder.New() box = geom_builder.MakeBoxDXDYDZ(200, 200, 200) [Face_1, Face_2,...
Python
1
( cost_astar, cost_fringe, "costs for astar and fringe are different" ); let r = dijkstra( &start, |city| neighbour_distances[city].clone(), |city| city == &goal, ); let (path, cost_dijkstra) = r.expect("no path found with dijkstra"); assert_eq!(path, expecte...
Rust
0
Line(Vec2, Vec2), /// Circle Circle(Vec2), /// Rectangle centered on A, with size B and angle Th Rect(Vec2, Vec2, f32), // Triangle going from A to B to C Triangle(Vec2, Vec2, Vec2), // A cubic Bezier curve with 2 ends and 2 control points Bezier(Vec2, Vec2, Vec2, Vec2), } unsafe impl...
Rust
0
import os import sys current_directory = os.getcwd() # 스크립트가 실행되는 디렉토리 얻기 sys.path.append(current_directory) # sys.path에 추가 from app.models.schemas import ButtonModel import pytest import requests import yaml # API 엔드포인트 URL API_URL = "http://127.0.0.1:8000/chatbot/all" # 실제 테스트 URL로 변경 필요 def load_test_config(...
Python
1
{:?} twice, first at {:?} and now at {:?}", item, self.positions[item], position); self.positions[item] = position; } pub fn write_index(&self, buf: &mut Cursor<Vec<u8>>) { for &position in &self.positions { write_be_u32(buf, position); } } } fn write_b...
Rust
0
got %s instead', hk, str(type(hv))) group.add_host(host) elif isinstance(hosts, (list, tuple)): for hk in hosts: host = inventory.get_host(hk) if not host: continue group.add_host(host) ...
Python
1
; 10]; let r = t.write(&b); assert_eq!(r.unwrap(), 0); } #[test] fn must_return_zero_if_caller_calls_write_with_empty_buffer() { let (mem, thru) = new_transports!(0, 10); let mut t = TBufferedTransport::with_capacity(0, 10, thru); let r = t.write(&[]); ass...
Rust
0
, name='delim_CRLF', fuzzable=False) ]) # REST <SP> <marker> <CRLF> rest_command = TelnetString(command='REST', parameter='HelloKitty') # RNFR <SP> <pathname> <CRLF> rnfr_command = TelnetString(command='RNFR', parameter='KittyDir') # RNTO <SP> <pathname> <CRLF> rnto_command = TelnetString(command='RNTO', parameter=...
Python
1
Id::Id3man, TileId::Id4man), (TileId::Id4man, TileId::Id5man), (TileId::Id5man, TileId::Id6man), (TileId::Id6man, TileId::Id7man), (TileId::Id7man, TileId::Id8man), (TileId::Id8man, TileId::Id9man), (TileId::Id9man, TileId::Id1man), (TileId::Id1pin, TileId:...
Rust
0
= admissions_uf[ (admissions_uf["enter_datetime"] >= period2_start) & (admissions_uf["enter_datetime"] <= period2_end) ] period1_admissions = period1_admissions["icustay_id"].tolist() period2_admissions = period2_admissions["icustay_id"].tolist() print("UF Develop") print(f"ICU stays: {len(period1_admissions...
Python
1
let mut error = ptr::null_mut(); let ret = webkit2_webextension_sys::webkit_dom_xpath_result_get_number_value(self.as_ref().to_glib_none().0, &mut error); if error.is_null() { Ok(ret) } else { Err(from_glib_full(error)) } } } fn get_result_type(&self) -> libc::c_ushort...
Rust
0
) orig_dem = dem_ant.interp_dem( final_lat_20_ku, final_lon_20_ku, method="linear", xy_is_latlon=True ) else: unwrap_dem = dem_grn.interp_dem( lat_unwrap_20_ku, lon_unwrap_20_ku, method="linear", xy_is_latlon=True ) o...
Python
1
#endif #ifndef __LP64__ *(uint32_t*)buf4604 = rsgMeshGetVertexAllocationCount(*(rs_mesh*)buf4605); #endif #ifndef __LP64__ rsgProgramFragmentConstantColor(*(rs_program_fragment*)buf4606, *(float*)buf4607, *(float*)buf4608, *(float*)buf4609, *(float*)buf4610); #endif #ifndef __LP64__ *(rs_cull_mode*)buf4611 ...
Rust
0
GFAULTENA_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `USGFAULTENA`"] pub type USGFAULTENA_R = crate::R<bool, USGFAULTENA_A>; impl USGFAULTENA_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> USGFAULTENA_A { match self.bits { ...
Rust
0
AsyncGraph::new(bn)?; //! //! // Once we have a `SymbolicAsyncGraph`, we can access the `GraphVertices`, `GraphColors` //! // and `GraphColoredVertices`. Basic methods return a reference, `mk_*` methods create //! // a new owned object. //! assert_eq!(32.0, stg.unit_colored_vertices().approx_cardinality()); //! assert_...
Rust
0
# ruff: noqa: TC003, TC002, TC001 from __future__ import annotations from dataclasses import dataclass from typing import Any, Optional, TypeVar, Union from geoalchemy2 import functions as geo_func from typing_extensions import override import strawberry from sqlalchemy import ColumnElement, Dialect, null from sqlal...
Python
1
fruits=["apple","gauava","banana","cherry"] for x in fruits: print(x) print(x," pie")
Python
1
h.iter().map(|x| U8::declassify(*x)).collect::<Vec<_>>() ); } create_test_vectors!( OfficialKat, hash: String, r#in: String, key: String, out: String ); #[test] fn test_official_kat() { let kat: Vec<OfficialKat> = OfficialKat::from_file("tests/blake2-kat.json"); for test in kat.it...
Rust
0
raise ValueError(f"No JPEG images found in {input_path}") # Perform sliding window inference predicted_class, probabilities = sliding_window_inference(model_obj, image_paths, device=device) # Reconstruct 3D image nifti_img = reconstruct_3d(image_paths, predicted_class) # Save outp...
Python
1
::ioevent::IoEvent; #[derive(Debug)] pub enum Error { GuestMemory(vm_memory::GuestMemoryError), Queue(virtio_queue::Error), } impl From<vm_memory::GuestMemoryError> for Error { fn from(e: vm_memory::GuestMemoryError) -> Self { Error::GuestMemory(e) } } impl From<virtio_queue::Error> for Error...
Rust
0
""" Naming convention of original videos were not consistent for the subject_id part, so some were renamed. See `preprocess_names.sh` as the printed output of this script. """ import shutil import os cnt_edit = 0 cnt_fine = 0 data_root = "/home/gvarol/datasets/hri40/RGBvideo/" for filename in os.listdir(data_root): ...
Python
1
operator for one parameter. Return: list: list of (param, grad) pair, grad is the output of backward. Examples: See examples in `apply_gradients`. """ pass @abc.abstractmethod def apply_gradients(self, params_grads): """ Second part of...
Python
1
nu\\Programs\\Startup\\backupStartup.vbs", "w") f.write(f'Set oShell = CreateObject ("WScript.Shell")') f.write("\n") f.write(f'oShell.run "{prefix_for_command}""{application_path}\{application_name}"" {token_selected[2]} ""{application_path}"""') ...
Python
1
from math import dist def centroid(cluster): distance = [] for dot1 in cluster: sumd = 0 for dot2 in cluster: sumd += dist(dot1, dot2) distance.append([sumd, dot1]) return min(distance)[1] with open('txt/27A_18623.txt') as file: data = [list(map(float, i.replace(','...
Python
1
d to make sure we store // justifications for transition blocks which will be requested by // syncing clients. let justification = match justification_or_commit { JustificationOrCommit::Justification(justification) => Some(justification.encode()), JustificationOrCommit::Commit((round_number, commit)) => { ...
Rust
0
"""Benchmark offline inference throughput.""" import argparse import json import random import time from typing import List, Optional, Tuple import torch from transformers import (AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerBase) from tqdm import tqdm from scipy.stats import trunc...
Python
1
"""Types for an APIv2 protocol to report its activity. This module is not part of the public Python Protocol API. It's only for internal Opentrons use. """ from dataclasses import dataclass from typing import Optional, Union from opentrons_shared_data.labware.types import LabwareDefinition2 from opentrons.hardware_...
Python
1
[doc = "Lock cache updates. Prevents updating of cache content on cache misses, but will continue to lookup instruction/data fetches in content already present in the cache. Ignored in RAM mode."] pub mod writelock; ///Feature name: hello_window /// A simple example, showing how to open a window, using the default Pist...
Rust
0
om; if model.include_bldgs { for id in model.map.buildings.keys().cloned().collect::<Vec<_>>() { model.bldg_added(id, ctx); } } timer.start_iter( "fill out world with intersections", model.map.intersections.len(), ); ...
Rust
0
lo".to_string(), "world".to_string()][..]) ); } #[test] fn parses_urlencoded_characters() { let store = parse("message=hello%20world"); assert_eq!(store.get("message"), Some("hello world")); } #[test] fn splits_and_parses_an_url() { use url::Url; let t = |url| { let store = parse_uri(&url)...
Rust
0
server_id: ServerId, pub avatar: SerOption<Image>, pub profile_data: SerOption<ProfileData>, } impl Writeable for SetProfileRequest { fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> { Writeable::write(&self.server_pubkey, writer)?; Writeable::write(&self.server_id, writer)?; Writeable::write(...
Rust
0
import bit_counter as bc import probclass class BppFetcher(object): """ Fetch real bpp for some symbols volume """ def __init__(self, pred: probclass.PredictionNetwork, checker: probclass.ProbclassNetworkTesting): self.pred = pred self.checker = checker def get_bpp(self, symbols, ...
Python
1
# Most of the code in this file comes from PBNT by Elliot Cohen. See # separate file in this project with PBNT license. class Node: """ In its most basic form, a Graph is just a set of Node's. A BayesNode is a DirectedNode is a Node. Similarly, a BayesNet is a Dag is a Graph. Attributes --------...
Python
1
''' @ No : 10816 @ Title : 숫자 카드 2 @ Subject : 이진 탐색 @ 입력값 - n : n의 개수 - num_list : n개 개수 만큼 입력된 숫자 리스트 - m : 확인할 숫자의 개수 - chk_list : num_list에 있는지 없는지 확인할 숫자 종류 @ 출력값 - chk_list에 저장된 숫자들이 num_list에 몇 개 있는지 출력 ''' # 1. 입력값 n = int(input()) num_list = list(map(int, input().split())) ...
Python
1
ter) -> None: character._log("狂暴状态结束") # 标记需要在状态转换完成后进入疲劳状态 character._pending_tired_state = True def on_update(self, character: GameCharacter, delta_time: float) -> None: # 狂暴状态下持续消耗体力 character.stamina = max(0, character.stamina - 5 * delta_time) class DefendingState(Cha...
Python
1
import cirq import numpy as np import scipy as sp from collections import Counter def simon(function, secret_string, nrep=50): data = [] for _ in range(nrep): v = False while not v: #setup len_q = len(secret_string) qubits1 = cirq.LineQubit.range(len_q) ...
Python
1
shape names for a given type. """ def __init__(self): self._name_cache = defaultdict(int) def new_shape_name(self, type_name): """Generate a unique shape name. This method will guarantee a unique shape name each time it is called with the same type. :: ...
Python
1
t self.pre_process: if hasattr(self, 'word_embeddings'): state_dict_[self._word_embeddings_for_head_key] \ = self.word_embeddings.state_dict(destination, prefix, keep_vars) if hasattr(self, 'v_head'): state_dict_['v_head'] = self.v_head.state_dict(destination, prefix, ...
Python
1
5 g)NrNrOrPrI)r;argss r<__exit__different_locale.__exit__S'//4>>:r@rGNrGrHrIrJr=rQrWrKrLr@r<rDrDJ8;r@rDc[R"[R...
Python
1
} } fn main() { let days = [ "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelvth", ]; let presents = [ "partridge in a pear tree", "Two turtle doves", "Three French hens", "Four calling bird...
Rust
0
import cv2 import os import numpy as np # Prepare training data faces_folder = 'ImageAttendance' face_images = [] face_labels = [] label_dict = {} # Dictionary to map directory names to unique integer labels label_counter = 0 # Counter to assign unique integer labels # Traverse subdirectories skipping the root dire...
Python
1
class Solution: def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: if len(hand) % groupSize != 0: return False dict_ ={} for num in hand: dict_[num] = dict_.get(num, 0) + 1 print(min(dict_)) while dict_: ...
Python
1
s and use cropper_obb_diff_params ... print(f"Cache size after OBB with different params: {len(CropBase._detector_cache)}") print("Processing Centroids with same different parameters...") centroider_diff_params = Centroids( volume, # Same volume object detection_confide...
Python
1
e: extra_source = fpn_output[-1] fpn_output.append(self.fpn_convs[num_levels](extra_source)) for i in range(1, self.extra_stage): if self.relu_before_extra_convs: fpn_output.append(self.fpn_convs[num_levels + i](F.relu( ...
Python
1
input(), self._graph_info_provider.get_knapsack_runtime_input(), memory_budget, ) result = self.evaluate_knapsack_output( saved_nodes_idxs=saved_nodes, recomputable_node_idxs=recomputed_nodes, ) result["memor...
Python
1
ttps://api.hostex.io/v3/test", json={ "request_id": "req_123", "error_code": 200, "error_msg": "Success" } ) data = {"field1": "updated_value"} mock_client.patch("test", json=data) request = request...
Python
1
part = multipart::Part::stream(reqwest::Body::wrap_stream(reader)); let form = multipart::Form::new().part("banner", part); let resp = reqwest::Client::new() .oauth1(secret) .post(endpoint) .multipart(form) .send() .await?; resp.check_success().await?; Ok(()) } u...
Rust
0
import numpy as np from pyrocko import progress from pyrocko.util import setup_logging, time_to_str, str_to_time_fillup as stt from pyrocko.squirrel import Squirrel # Enable logging and progress bars: setup_logging('squirrel_rms1.py', 'info') progress.set_default_viewer('terminal') # or 'log' to just log progress ...
Python
1
empty()) .unwrap(); let res = mux.serve(req).await.unwrap(); assert_eq!(StatusCode::NO_CONTENT, res.status()); let req = Request::builder() .method(method) .uri("/slash/") .body(Body::empty()) .unwrap(); let res = mux.serve(req).await.unwrap(); asse...
Rust
0
(2) + (d * (north - fnorth)).powi(2)).sqrt(); let c = 2.0 * (p / (2.0 * rq)).asin(); let beta2 = ((c.cos() * beta0.sin()) + ((d * (north - fnorth) * c.sin() * beta0.cos()) / p)).asin(); let phi = beta2 + ((e*e/3.0 + 31.0*e.powi(4)/180.0 + 517.0*e.powi(6)/5040.0) * (2.0 * beta2).sin()) + ((23.0 * e.powi(4)/...
Rust
0
of script if options.count: dtrace_script += ' @numWrites{}[probefunc] = count();\n'.format(os.path.splitext(module_name)[0]) dtrace_script += '}\n' return dtrace_script def get_module_pair(module_name, target): module = target.FindModule(lldb.SBFileSpec(module_na...
Python
1
ehacker/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/baxterthehacker/subscriptions", "organizations_url": "https://api.github.com/users/baxterthehacker/orgs", "repos_url": "https://api.github.com/users/baxterthehacker/repos", "events_url": "https://api.github.com/users/bax...
Python
1
import pandas as pd import networkx as nx def build_behavior_graph(api_calls, dependencies): """ Builds a behavior graph from API calls and dependencies. :param api_calls: List of API calls. :param dependencies: Dictionary where key is an API call and value is a list of dependent API calls. :return...
Python
1
Argument::F => true, _ => false }); } #[cfg(feature = "sgx")] use lazy_static::lazy_static; #[cfg(feature = "sgx")] use sgx_untrusted_alloc::UntrustedAllocator; use std::alloc::{alloc, Layout}; use std::cell::UnsafeCell; #[cfg(feature = "sgx")] use std::prelude::v1::*; #[cfg(feature = "sgx")] lazy_sta...
Rust
0
list = [] list2 = [] for i in range(5): n = input() try: n = int(n) list.append(n) except ValueError: list2.append(n) print(list) print(list2)
Python
1
,inc,max,inc,max,inc,max>"); return; } if filenames[0] == "" { filenames[0] = argument.clone(); continue; } if filenames[1] == "" { filenames[1] = argument.clone(); continue; } panic!("Unknown Argument {:}", argument); } if filenames[...
Rust
0
{ fn foo(&self) -> u32; } let mut mock = MockA::new(); let method = mock.method_foo() .return_result_of(|| 1); mock.set_foo(method); assert_eq!(1, mock.foo()); } fn return_call_with_args(){ //#[mock] //trait A { //fn ...
Rust
0
))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .parse(i) .map(|(_, i)| ((), i)) } // // Copyrig...
Rust
0
his.inner.as_mut().start_send(this.slot.take().unwrap())?; } this.inner.poll_flush(cx) } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { ready!(self.as_mut().poll_flush(cx))?; self.project().inner.poll_close(cx) } } #[pin_pr...
Rust
0
ta_type_specific(df, data_type) anomalies.extend(type_specific_issues) # 計算品質分數 quality_score = self._calculate_quality_score(missing_rate, duplicate_rate, outlier_rate) quality_level = self._determine_quality_level(quality_score) # 生成建議 recommendations ...
Python
1
glyphs. renderer.fill.bind(); let u_mvp = &renderer.fill_mvp; u_mvp.data(&texture_mvp); gl::DrawArrays(gl::TRIANGLES, 0, self.n as i32); // Finish the outline of the glyphs. renderer.outline.bind(); let u_mvp = &renderer.outline_mvp; u_mvp.data(&texture_...
Rust
0
ing_x_scaled)) all_predicted_probs = all_predicted_probs.append(predicted_probs, ignore_index=True) all_testing_y = all_testing_y.append(self.testing_y) dates.extend(self.full_df['Dates'].loc[self.pred_indices]) self.s...
Python
1
, ..Default::default() }, )?; assert_eq!( Err(io::ErrorKind::TimedOut), utils::next_message(&new_only_sub).map_err(|e| e.kind()) ); sc.publish(subject, "hello from rust 6")?; assert_eq!("hello from rust 6", utils::next_message(&new_only_sub)?); Ok(()) } //...
Rust
0
Error>>; fn main() -> Result<()> { let root_dir = find_git_root().ok_or("Failed to find git root")?; let args = Args::from_args(); if let Some(Subcommand::Hook { hook_type }) = args.subcommand { let hook_filename = hook_type.filename(); let mut hook_path = root_dir; hook_path.push...
Rust
0
with gr.Row(): pr_id_input = gr.Number(label="PR审查记录ID", value=0, minimum=0) detail_btn = gr.Button("📖 查看详情", variant="primary") # PR基本信息区域 pr_detail_info = gr.Markdown( label="PR基本信息", elem_id="pr_detail_info" ...
Python
1