text
string
label_name
string
labels
int64
function `f`. This mutation must not /// change the sort-order of keys. #[inline] pub fn offset_keys<F>(&mut self, f: F) where F: Fn(&mut K) { self.data.iter_mut().map(|&mut (ref mut k, _)| k).for_each(f); } /// Inserts a presorted range of elements into the map. If the range c...
Rust
0
", "get_fft_backend", "safe_fft", "safe_ifft", "robust_fft", "robust_ifft", "_get_fractional_kernel", "spectral_fractional_derivative", "fractional_derivative", "SpectralFractionalDerivative", "SpectralFractionalFunction", "SpectralFractionalLayer", "SpectralFractionalNet...
Python
1
m, device=metric_tensor.device).unsqueeze(0) identity_error = torch.norm(identity_approx - identity_target, dim=(1, 2)) print(f"✅ G * G_inv ≈ I error: mean={identity_error.mean():.3e}, max={identity_error.max():.3e}") return metric_tensor def test_compatibility_with_original(metric_tensor: MetricTens...
Python
1
: H256Le, error: ErrorCode, ) -> UnitResult { <btc_relay::Module<T>>::flag_block_error(block_hash, error) } pub(crate) fn clear_block_error<T: btc_relay::Trait>( block_hash: H256Le, error: ErrorCode, ) -> UnitResult { <btc_relay::Module<T>>::clear_block_error(blo...
Rust
0
# -*- coding: utf-8 -*- """policy_model_training.ipynb Automatically generated by Colab. Original file is located at https://colab.research.google.com/drive/1i5t3G3n1GUzD0qt9Jc8UlLXzDNgfqz64 """ #!/usr/bin/env python # 2025‑05‑04 – PPO training (v9.3‑mod4‑resume‑5chk) # • five checkpoints / epoch (20 %,40 %,60 ...
Python
1
i_name("Hack.Lang.AllowUnstableFeatures", true), "hhvm.hack.lang.allow_unstable_features" ); assert_eq!( HhvmConfig::ini_name("Server.SSLPort", false), "server.ssl_port" ); assert_eq!(HhvmConfig::ini_name("PathDebug", false), "path_debug"); } #[derive(Clone, Debug)] pub struct P...
Rust
0
ountsCmd { pub fn execute(&self, accounts: &Vec<AddressedAccount>) -> Result<(), Error> { for account in accounts { let mut buf = [0u8; 32]; account.0.to_big_endian(&mut buf); println!("0x{}", hex::encode(buf)); } Ok(()) } } <filename>aoc2015/src/lib....
Rust
0
, src1: Reg /*32*/, src2: Reg /*32*/) { self.internal_binop("UMNEGL", dest, src1, src2) } fn emit_umull(&mut self, dest: Reg /*64*/, src1: Reg /*32*/, src2: Reg /*32*/) { self.internal_binop("UMULL", dest, src1, src2) } fn emit_adc(&mut self, dest: Reg, src1: Reg, src2: Reg) { se...
Rust
0
{2x_0zz_0}{y_0^2} + (\frac{zz_0}{y_0})^2 - (x_0^2 + y_0^2) /// \end{array} /// \right. /// ``` /// We solve the quadratic equation /// ```math /// \left\{ /// \begin{array}{rcl} /// ax^2 + bx + c & = & 0 \\ /// \Delta & = & b^2 - 4ac \\ /// x & = & \frac{-b\pm \sqrt{\Delta}}{2a} /// \end{array} /// \...
Rust
0
"] Data(u64), #[db_name = "S"] SubObject(TestStruct), #[db_name = "E"] #[inner_model = "enum"] SubEnum(TestSimpleEnum), } ); #[test] fn x() { let x = serde_json::to_string(&ApiTestSimpleEnum::Data).unwrap(); println!("{}", x); let x = serde_json::to_st...
Rust
0
load_json() return car_preset # --- Data Setter ends here --- # # --- Helper data getter/setter here --- # def check_is_player_data_complete() -> None: global json_data is_write = False player_data = ( json_data.get("root", {}) .get("properties", {}) .get("use...
Python
1
self.num_banks_prg >> 1); self.mirror_mode = if (data & 0x10) == 0 { Mirror::OneScreenLo } else { Mirror::OneScreenHi }; } MapResult::None } fn ppu_map_read(&mut self, addr: u16) -> MapResult { match addr { ...
Rust
0
egory_styles() assert comp_styles == ctrl_styles def test_category_fallback_behavior(self, sample_controls, sample_components): """Test fallback behavior when category configuration is missing.""" # Create a control graph and test fallback category naming graph = ControlGraph(sampl...
Python
1
NN = time.time() B_m = np.zeros(shape=(M_m.shape[0], int((M_m.shape[0]-1)/2)+1)) res = model.predict(data_M) i = 0 j = 0 # Left Boundary # patch = res[0, :] # B[i:i+3, j] = patch[:3] # B[i:i+5, j+1] = patch[3:8] # B[i+2, j+2] = patch[8] # # # # i = i + 2 # # j = j + 1 # for k in range(0, res.shape[0]): patch = re...
Python
1
t(config: &Config, release: bool, debounce_time: Duration) -> Self { let (watcher, debounced_receiver) = ProjectWatcher::start(&config.watch.frontend, debounce_time) .context("Failed to start the frontend project watcher")?; let reload_url = Arc::new(format!( "{p...
Rust
0
from setuptools import setup import os def read_version(): version_file = os.path.join(os.path.dirname(__file__), 'TM1_bedrock_py', '__init__.py') with open(version_file, 'r') as f: for line in f: if line.startswith('__version__'): delim = '"' if '"' in line else "'" ...
Python
1
Grass, Dirt, Stone, } impl Voxel {} #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RawMqttEvent { pub battery: u8, pub humidity: f32, pub temperature: f32, pub voltage: u16, pub linkquality: Option<u8>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize...
Rust
0
import os import torch import ctypes import numpy as np from glob import glob from cuda import cudart import tensorrt as trt import MobileViT_Pytorch.utils as utils import MobileViT_Pytorch.models as models from imagenet_lmdb_datasets import get_test_data from convert_to_onnx import get_net if __name__=='__main__': ...
Python
1
coeffs = self.coefficients.borrow_mut(); if element.val == 0 && idx >= coeffs.len() { return } if idx >= coeffs.len() { while idx >= coeffs.len() { coeffs.push(FiniteFieldElement::new(element.field_size, 0)) } } coeffs[idx] = el...
Rust
0
self.rewards[id_s, id_a, nds] = reward if self.mode == 'linear': for i in range(len(nds)): self.transitions[id_s, id_a, nds[i]] = probs[i] self.rewards[id_s, id_a, nds[i]] = reward def add_done_transitions(self): """ ...
Python
1
eave_multicast_group_with_no_hermetic_network_realm", &sandbox) .expect("failed to create netstack realm"); let network_test_realm = realm .connect_to_protocol::<fntr::ControllerMarker>() .expect("failed to connect to network test realm controller"); assert_eq!( network_tes...
Rust
0
EXP_SYSTEM_PROMPT = """ You're an expert judge who can give high quality rating for user's work experience to the given job description. A high score indicates that the user's work experience is highly relevant to the job description and vice-versa. """ EXP_PROMPT = """ Rate out of 10 for the given user's work experi...
Python
1
o_owned(), file: "benches/10k.inp".to_owned(), }, E2eTest { name: "star-count-parse-count".to_owned(), query: "* | count | parse '*' as k | count by k".to_owned(), file: "benches/1k.inp".to_owned(), }, ]; tests.into_iter().for_each(|test| {...
Rust
0
import scrapy class NotebookSpider(scrapy.Spider): name = "notebook" allowed_domains = ["lista.mercadolivre.com.br"] start_urls = ["https://lista.mercadolivre.com.br/notebook?sb=rb#D[A:notebook]"] page_count = 1 max_page = 10 def parse(self, response): products = response.css('div.ui...
Python
1
source)?; } Ok(()) } <gh_stars>100-1000 use syn::{Field, Ident, Meta}; use crate::options::{Core, DefaultExpression, ForwardAttrs, ParseAttribute, ParseData}; use crate::util::PathList; use crate::{FromMeta, Result}; /// Reusable base for `FromDeriveInput`, `FromVariant`, `FromField`, and other top-level /// ...
Rust
0
e: if attention_mask.shape[-1] != query.shape[1]: target_length = query.shape[1] attention_mask = F.pad(attention_mask, (0, target_length), value=0.0) attention_mask = attention_mask.repeat_interleave(self.heads, dim=0) # attention, what we cannot get...
Python
1
} write!(f, ">") } Ty::Self_(_) => write!(f, "Self"), Ty::Unsupported => write!(f, "_"), } } } /// Compatible type for syntax::ast::PatKind /// but currently doesn't support all kinds #[derive(Clone, Debug, PartialEq)] pub enum Pat { Wi...
Rust
0
let n = 5000; let epsilon: f64 = 0.01; let mut s = FixedSizeEpsilonSummary::new(n, epsilon); for i in 1..=n { s.update(i); } s } fn bench_gk_quantile_query(s: &mut greenwald_khanna::Stream<usize>) { for rank in [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] { s.quantil...
Rust
0
""" ¿Está en Equilibrio la Alianza entre Reed Richards y Johnny Storm? En el universo de los 4 Fantásticos, la unión y el equilibrio entre los poderes es fundamental para enfrentar cualquier desafío. En este problema, nos centraremos en dos de sus miembros: Reed Richards (Mr. Fantastic), representado por la letra R. ...
Python
1
from ipari_forradalom import IpariForradalom # Quiz létrehozása def ipari_forradalom_quiz(forradalom): print("Ipari Forradalom Quiz") print("---------------------") print("Kérdés:") print(f"Mikor kezdődött az {forradalom.evszam} ipari forradalom?") print("A) 1600-as évek\nB) 1700-as évek\nC) 1800-a...
Python
1
clone_empty() { let v = HeaderVec::<_, i32>::new("foo"); assert_eq!(v.clone(), v); } #[test] fn clone_zst() { let v = header_vec!["foo"; (); 5]; assert_eq!(v.clone(), v); } #[test] fn default() { let v = HeaderVec::<bool, i32>::default(); assert_eq!(v, header_vec![false;]); } <reponame>donmcc...
Rust
0
which establishes Mojo connection in libvda. let dev_urandom_path = Path::new("/dev/urandom"); jail.mount_bind(dev_urandom_path, dev_urandom_path, false)?; let system_bus_socket_path = Path::new("/run/dbus/system_bus_socket"); jail.mount_bind(system_bus_socket_path, syst...
Rust
0
, u64::MAX, ) .unwrap_err() .raw_os_error(), libc::EINVAL ); } } #[test] fn test_mmap_anonymous() { use rustix::mm::{mmap_anonymous, munmap, MapFlags, ProtFlags}; use std::ptr::null_mut; use std::slice; unsafe { let ad...
Rust
0
if Dot2(u, u) == 0.0 or Dot2(v, v) == 0.0: return False else: pp2 = Perp2(w, v) if abs(pp2) > TOL: return False # parallel, not collinear z = Sub2(b, c) (vx, vy) = v (wx, wy) = w (zx, zy) = z if vx ...
Python
1
ISING_EDGE, 2 => BLE_IN_PROCESS_EVENT_A::BLE_IN_PROCESS_EVENT_FALLING_EDGE, 3 => BLE_IN_PROCESS_EVENT_A::BLE_IN_PROCESS_EVENT_TRANSITION, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `BLE_IN_PROCESS_EVENT_NONE`"] #[inline(always)] pub ...
Rust
0
# -*- coding: utf-8 -*- """ Created on Wed Feb 5 15:13:05 2025 @author: stris """ from apt_interface.KSG101 import KSG101, KSG101Config from time import sleep with KSG101(config_file="conf/config_KSG.yaml") as ksg: print(ksg.conf) print(ksg.get_max_travel()) ksg.identify() while True: p...
Python
1
import time import pytest from marie import Document, DocumentArray, Executor, Flow, requests @pytest.mark.parametrize( 'shards, expected_response', [(1, ['slow', 'fast']), (2, ['fast', 'slow'])] ) def test_non_blocking_gateway(shards, expected_response): class FastSlowExecutor(Executor): def __init...
Python
1
let path = format!("/v1/withdrawal/{}", id); client.get(&path, None as Option<String>).await } /// Retrieve withdrawals. pub async fn list_withdrawals(client: &Client) -> Result<Vec<Withdrawal>, Error> { client.get("/v1/withdrawals", None as Option<String>).await } /// Create refund pub async fn create_r...
Rust
0
light = "green" if (light == "green"): print("Go") elif (light == "red"): print("Stop") else: print("Slow down") print("End of program") # Output: # Go # else can only be written once in an if-elif-else statement. # In this example, the light is green, so the output is "Go". # If the light was...
Python
1
mut CaseTypeIterator::Camel(ref mut it) => it.next(), &mut CaseTypeIterator::Delimeter(ref mut it) => it.next(), } } } impl<'a, 'b> DefiningCase<'a, CaseTypeIterator<'a>> for &'b CaseType { fn components_iter(self, src: &'a str) -> CaseTypeIterator<'a> { match *self { Ca...
Rust
0
& (1 << 1) == 0b0000_0010 { p_four = p_four | 1 << 1; } // set bit 2 if sbox_zero_val & (1 << 0) == 0b0000_0001 { p_four = p_four | 1 << 2; } //set bit 3 if sbox_zero_val & (1 << 1) == 0b0000_0010 { p_four = p_four | 1 << 3; } //println!("joined_bits: {:04b}_bin", p_four); // F(R, SK...
Rust
0
') and job.get('job_company_name') and job.get('job_id'): job_instance = Job( job_title=job.get('job_title'), job_company_name=job.get('job_company_name'), job_level=job.get('job_level'), job_description=job.get('job_descrip...
Python
1
1 = V3([1.0, 0.0, 0.0]); let v2 = V3([2.0, 0.0, 0.0]); let v3 = V3([2.0, 1.0, 0.0]); let v4 = V3([0.0, 0.0, -1.0]); assert_eq!(v1.are_independent(&v2), false); assert_eq!(v1.are_independent(&v3), true); assert_eq!(v1.are_independent(&v4), true); } } <filename>examples...
Rust
0
write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [autocolresconfig](autocolresconfig) module"] pub type AUTOCOLRESCONFIG = c...
Rust
0
[1]), [1]) self.assertEqual(loader.select_many({}, default_value={}), {}) self.assertEqual(loader.select_many({}, default_value={'a': 1}), {'a': 1}) self.assertEqual(loader.select_many({}, default_value=1), [1]) self.assertEqual(loader.select_many({}, default_value='a'), ['a']) self.assertEqual(load...
Python
1
----------') print('L_DC [nH] :', str(Lseries[1]*1e9)) print('R_DC [Ohm]:', str(Rseries[0])) print('Peak Q :', str(max(Q))) # create Touchstone S1P output file in simulation data path #s1p_name = os.path.join(sim_path, model_basename + '.s1p') #s1p_file = open(s1p_name, 'w') ...
Python
1
current_time = datetime.now() # Clean old attempts (older than 1 hour) self.failed_attempts[identifier] = [ attempt_time for attempt_time in self.failed_attempts[identifier] if current_time - attempt_time < timedelta(hours=1) ] self.failed_atte...
Python
1
hetas, thetas[theta_layer_index].flatten())) return unrolled_thetas @staticmethod def thetas_roll(unrolled_thetas, layers): """Rolls NN params vector into the matrix""" # Get total numbers of layers. num_layers = len(layers) # Init rolled thetas dictionary. th...
Python
1
2 => ShoulderStabilityExerciseName::BandInternalRotation, 3 => ShoulderStabilityExerciseName::BentArmLateralRaiseAndExternalRotation, 4 => ShoulderStabilityExerciseName::CableExternalRotation, 5 => ShoulderStabilityExerciseName::DumbbellFacePullWithExternalRotation, ...
Rust
0
iting with pandas took __min loc_path = self.fn_path # write groups group_dict = dict( data[["particlegroup", "groupname"]].itertuples(False, None) ) # writing group loc data groups = ( data[["particlegroup", "groupname"]] .groupby("pa...
Python
1
OP_EXT: Self = BlendOp(1_000_148_009); } #[doc = "Generated from \'VK_EXT_blend_operation_advanced\'"] impl BlendOp { pub const DST_ATOP_EXT: Self = BlendOp(1_000_148_010); } #[doc = "Generated from \'VK_EXT_blend_operation_advanced\'"] impl BlendOp { pub const XOR_EXT: Self = BlendOp(1_000_148_011); } #[doc = ...
Rust
0
fs::remove_dir_all("frames")?; fs::create_dir("frames")?; println!("{}", "`frames` already existed, deleted.".yellow()); } } } println!("extracting frames via ffmpeg..."); let command = Command::new("ffmpeg") ...
Rust
0
def check_area(i, j, mat, park): if i+mat > len(park) or j+mat>len(park[0]): return False for r in range(i, i+mat): for c in range(j, j+mat): if park[r][c] != "-1": return False return True def solution(mats, park): # 1. mats 내림차순 정렬 mats.so...
Python
1
import os from pathlib import Path from PIL import Image from tqdm import tqdm def visdrone2yolo(dir): def convert_box(size, box): # Convert VisDrone box to YOLO CxCywh box,坐标进行了归一化 dw = 1. / size[0] dh = 1. / size[1] return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, b...
Python
1
} ) ) } impl TreePrinter for MemberAccess { fn print(&self, level: usize) { let p = prefix(level); println!("{}member access (span: {}, type: {})", p, self.span, self.typ); self.left.print(level + 1); match self.right { MemberAccessT...
Rust
0
x0, 0x1c0)) ); assert_eq!( vFile::parse(BytesMut::from(&b":pread:b,1000,0"[..])), Some(vFile::Pread(0xb, 0x1000, 0x0)) ); assert_eq!( vFile::parse(BytesMut::from(&b":unlink:6a7573742070726f62696e67"[..])), Some(vFile::Unlink(PathBuf::from("...
Rust
0
current_span() .await? { region_row.get("id") } else { sqlx::query("INSERT INTO regions(name) VALUES(?) RETURNING id") .bind(region) .fetch_one(pool) .in_current_span() ...
Rust
0
0,0,0,0,0,0,0, 0,0,1,0,2,0,3,1], &[0xed,8,100,6,1,1,2, 0,2, 0xd4,1,2,3,1]); check_packing(&[0; 16], &[0,1]); check_packing(&[0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0], &[0,2]); } #[test] #[cfg_attr(miri, ignore)] // miri takes a long time with quickcheck fn check_r...
Rust
0
let context = Arc::new( ContextAsync{ context: context , async_thread: Mutex::new(None), open_count: RwLock::new(0), }); Ok(Context {context}) } /// Sets the log level of a `libusb` context. pub fn set_log_level(&mut sel...
Rust
0
return Some(*c); } } e => panic!("invalid character: {}", e), } } None } fn get_autocomplete_score(chrs: &[char]) -> usize { let mut stack = vec![]; for c in chrs.iter() { match c { '[' | '(' | '{' | '<' => stack.push(c), ']' | ')' | '}' | '>' => { if st...
Rust
0
ce_command' not in st.session_state: st.session_state.voice_command = "" if 'speak_message' not in st.session_state: st.session_state.speak_message = None st.set_page_config(page_title="AIShopmate", layout="wide") st.title("🛒 AIShopmate – Smart Budget-Aware Cart") # Step 1: Budget input with st.sidebar: ...
Python
1
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/gui/Scaleform/daapi/view/battle/ranked/players_panel.py from constants import ARENA_PERIOD from gui.Scaleform.daapi.view.battle.ranked.ranked_voip_helper import RankedVoipHelper, VoiceChatControlTextStyles from gui.Scaleform.daapi.v...
Python
1
if round < N { accumulator = result.array[round].to_double(); } accumulator = accumulator + mul_res + carry; if accumulator > t_max { carry = accumulator >> Self::WORD_BITS; accumulator =...
Rust
0
: student_opt.param_groups[0]['lr'], 'teacher train ppl': math.exp(t_cur_loss), 'student train ppl': math.exp(s_cur_loss)}, step=train_step) t_total_loss = 0 s_total_loss = 0 start_time = time.time() if train_step % args.eval_interval == 0: val_losse...
Python
1
from playwright.sync_api import Playwright, sync_playwright, expect from playwright_stealth import stealth_sync from browserforge.injectors.playwright import NewContext from browserforge.fingerprints import FingerprintGenerator from bs4 import BeautifulSoup from core.captcha import ffmpeg_converter, speech_to_text impo...
Python
1
# -*- coding: utf-8 -*- # Copyright 2025 Google LLC # # 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...
Python
1
cle_count < max_cycles: print(f"Starting cycle {cycle_count + 1}") else: print("All cycles completed!") vel_command = torch.zeros(3) else: print(f"Cycle {cycle_count + 1}: Moving to target {cu...
Python
1
- Cos[41*Pi/128])*Sqrt[2] = 0.43820248031374 // 3099/4096 = Cos[41*Pi/128]*Sqrt[2] = 0.75660088988166 let (tk, tb) = RotateSub::half_kernel(tk, tbh, ((7993, 13), (14359, 15), (3099, 12))); // 16143/16384 = (Sin[39*Pi/128] + Cos[39*Pi/128])/Sqrt[2] = 0.98527764238894 // 2801/8192 = (S...
Rust
0
the Holy Ghost liveth and reigneth, one God, for ever and ever.") .response("Amen.") ) .label("Teresa of Avila") .source(Reference { source: Source::LFF2018, page: 0 }) .version(Ve...
Rust
0
def complete(self, *args, **kwargs): self.writer.close()
Python
1
rselet::new( test_name, CodeBodyParselet::new( builder() .keyword("let") .identifier("x") .assignment() .literal_int(42) .newline() .build(), ), ...
Rust
0
/ These should all be together and available if there's a split if let Some((left_end, at_value)) = at.before().zip(at.value()) { if split_range.0.contains(at_value) { // This should always unwrap, because we know the key exists let value = self.map.re...
Rust
0
ts.all() serializer_class = TripSerializer permission_classes = [IsAuthenticated, IsOrganizerOrReadOnly] def get_serializer_class(self): if self.request.method in ("PUT", "PATCH"): return TripCreateSerializer return TripSerializer def update(self, request, *args, **kwargs):...
Python
1
k performs mapping and correlation of vulnerabilities related to the identified versions (framework, libs, etc.), allowing you to interact with issues and create exploitability scenarios where other resources will be triggered. The framework is modular, allowing new modules (siddhis...
Python
1
from django import forms from documents.fields import SearchInput from documents.parsers import ParseError from documents.parsers.django_orm import DjangoORMParser from documents.parsers.dummy import DummyParser DOCUMENT_PARSER_BLANK = "" DOCUMENT_PARSER_DJANGO_ORM = "django-orm" DOCUMENT_PARSER_CHOICES = ( (DOC...
Python
1
pub async fn destroy(mut self) -> Result<(), Error> { let pid = self.child.id().unwrap(); self.child.kill().await.ok(); debug!("Joining perf pid {}", pid); self.child .wait() .await .map_err(|e| Error::io("Failed to join perf", e))?; Ok(...
Rust
0
} match instr { Instr::Nop => {} Instr::Store(index) => { let val = self.stack.pop().unwrap(); self.stack[self.stack_frame_offset + index] = val; } // todo: no no no no no no this is wrong Instr::Load(index) => self.sta...
Rust
0
es.LoggingConfig( logSeverity=self._messages.LoggingConfig.LogSeverityValueValuesEnum( logging_config ), ) def _ConvertSaslMechanismToEnum(self, mechanism): """Convert human-readable mechanism to enum.""" if mechanism == 'PLAIN': return self._messages.SaslAuthConfig.Mech...
Python
1
h markets are quoted in the same currency. Now suppose // one swaps A for B across A/USDC and B/USDC. Further suppose the first // leg swaps the entire *from* amount A for USDC, and then only half of // the USDC is used to swap for B on the second leg. How should we calculate // the exchange rate? /...
Rust
0
// } // println!("sended"); } pub async fn wait_for_send(socket: Arc<UdpSocket>, mut engine_rx: Receiver<Packet>) { // let mut interval = tokio::time::interval(tokio::time::Duration::from_millis(10)); loop { // interval.tick().await; if let Some(packet) = engine_rx.recv().await { ...
Rust
0
T_SET: continue perm = permission_model.objects.create( permission=permissions_dict[codename][0], **filter_kwargs ) if value == PermissionsForm.PERM_NOT_SET: perm.delete()...
Python
1
f should be able to figure out this bound Vec<T>: tree_buf::Decodable, { let start = Instant::now(); let logs = logs.iter().cloned().collect::<Vec<_>>(); let logs = logs.into_iter(); println!(); ChunkLoader { start, logs, current: None, _marker: PhantomData, ...
Rust
0
IE_NAME = 'safari:api' _VALID_URL = 'https?://(?:www\\.)?(?:safaribooksonline|(?:learning\\.)?oreilly)\\.com/api/v1/book/(?P<course_id>[^/]+)/chapter(?:-content)?/(?P<part>[^/?#&]+)\\.html' _NETRC_MACHINE = 'safari' class SafariCourseIE(SafariBaseIE): _module = 'yt_dlp.extractor.safari' IE_NAME = 'sa...
Python
1
_dir_all, File}; use std::io::Write; use std::path::PathBuf; use crate::command::Command; use crate::constants::{DOSH_CONF_NAME, DOSH_FOLDER_NAME}; #[derive(Clone)] pub struct Config { config_dir: PathBuf, } impl Config { pub fn new() -> Self { let config_dir = PathBuf::from(DOSH_FOLDER_NAME); ...
Rust
0
. pub trait IntoEnum<Enum, Index> { fn into_enum( self ) -> Enum; } impl<Enum,Variant,Index> IntoEnum<Enum, Index> for Variant where Enum: FromVariant<Variant, Index> { fn into_enum( self ) -> Enum { <Enum as FromVariant::<Variant, Index>>::from_variant( self ) } } /// Constructs an enum from ...
Rust
0
fn handle(&mut self, _msg: GetHeartbeatCount, _ctx: &mut Context<Self>) -> Self::Result { Ok(self.count) } } //! A module defining the `cl_context` related types, such as the high-level `Context` type. use wrapper::ffi; use wrapper::information::InformationResult; use wrapper::types::platform::Platform; u...
Rust
0
conditional_escrow::*; pub use crate::openzeppelin::contracts::generated::escrow::*; pub use crate::openzeppelin::contracts::generated::refund_escrow::*; } pub mod introspection { pub use crate::openzeppelin::contracts::generated::erc165::*; pub use crate::openzeppelin::contracts::generated::erc165...
Rust
0
\nreplaco3\nreplaceo4/g' INPUT_FILE.txt // sed "H;1h;\$\!d; x ; s/findo1\nfindo2\nfindo3\nfindo4/replaco1\nreplaco2\nreplaco3\nreplaceo4/g" INPUT_FILE.txt // https://unix.stackexchange.com/a/429141/402082 } pub struct Mutation; #[juniper::object(Context = Context)] impl Mutation { #[graphql(description = "Returns...
Rust
0
[repr(C)] #[derive(Copy, Clone)] pub union cudaKernelNodeAttrValue { #[doc = "< Attribute ::CUaccessPolicyWindow."] pub accessPolicyWindow: cudaAccessPolicyWindow, pub cooperative: ::libc::c_int, _bindgen_union_align: [u64; 4usize], } #[test] fn bindgen_test_layout_cudaKernelNodeAttrValue() { assert...
Rust
0
from currency_converter import CurrencyConverter import tkinter as tk a = CurrencyConverter() window = tk.Tk() window.geometry("1000x500") window.configure(bg="lightgreen") def clicked(): try: amount = float(e1.get()) cur1 = e2.get().upper() cur2 = e3.get().upper() data =...
Python
1
#!/usr/bin/env python """ synopsis: Hello World server in Python. Binds REP socket to Url. Expects b"Hello" from client, replies with b"World". Modified for tornado/ioloop: Dave Kuhlman <dkuhlman(at)davekuhlman(dot)org> usage: python hwserver.py """ import sys import zmq from zmq.eventloop.future ...
Python
1
unsafe fn _mm256_mask_mulhi_epu16( src: __m256i, k: __mmask16, a: __m256i, b: __m256i, ) -> __m256i { let mul = _mm256_mulhi_epu16(a, b).as_u16x16(); transmute(simd_select_bitmask(k, mul, src.as_u16x16())) } /// Multiply the packed unsigned 16-bit integers in a and b, producing intermediate 32-...
Rust
0
ait fallen.edit_text( f"⋄ انتظر من فضلك يتم اضافة حساب المساعد\n\n {ASS_NAME} في {message.chat.title}." ) try: await app2.join_chat(invitelink) await asyncio.sleep(2) await fallen.edit_text( f"{ASS_NAME} ⋄ تم الانضمام ✅,\n\n⋄ بدء التشغيل......
Python
1
""" Copyright 2013 Steven Diamond 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 writing, software...
Python
1
3. Validate interpolation method 4. Calculate coordinate ranges for grid and create uniform grid points 5. Interpolate intensities onto grid using griddata 6. Reshape result to 2D grid 7. Create phosphor colormap 8. Create figure and plot with colorbar, labels, and title 9. Show plot Examp...
Python
1
Padded projections tensor. """ pad_size = compute_pad_size(proj.shape[-2]) return pad(proj, [0,0,pad_size,pad_size], mode=mode, value=value) def unpad_proj(proj: torch.Tensor): """Unpads the projections back to original Lr dimensions Args: proj (torch.Tensor[batch_size, Ltheta, Lr', Lz]...
Python
1
= G.reverse(copy=True) assert H.nodes == self.MDG.nodes assert H.edges == self.MDG.edges def test_subgraph_edgesubgraph_toundirected(self): G = self.G.copy() SG = G.subgraph([4, 5, 6]) SSG = SG.edge_subgraph([(4, 5), (5, 4)]) USSG = SSG.to_undirected() asser...
Python
1
import json import sys import os print ".--=============--------------=============--." print "| Welcome to Image Matrix Maker! |" print ".--=============--------------=============--." yeswords = ["yes", "y", "ya", "ok", "okay"] try: from PIL import Image except: ans = raw_input("The Python Imag...
Python
1
fn block_connected(&self, block: &Block, height: u32) { let header = &block.header; let txdata: Vec<_> = block.txdata.iter().enumerate().collect(); log_debug!(self.logger, "New best block {} at height {} provided via block_connected", header.block_hash(), height); self.process_chain_data(header, Some(height), ...
Rust
0
&str, uid: &str, code: &str, value: &str) -> Result<()> { insert_into(monitor_logs::dsl::monitor_logs) .values(( monitor_logs::dsl::name.eq(name), monitor_logs::dsl::uid.eq(uid), monitor_logs::dsl::code.eq(code), monitor_logs::dsl::val...
Rust
0