text
string
label_name
string
labels
int64
32) as u16 } #[inline] pub const fn patch(self) -> u32 { self.0 as u32 } } impl From<(u16, u16, u32)> for Version { fn from(other: (u16, u16, u32)) -> Self { Self::new(other.0, other.1, other.2) } } impl fmt::Display for Version { fn fmt(&self, fmt: &mut fmt::Formatter) ->...
Rust
0
nums: &mut [i32]) { let mut len = nums.len() - 1; while len > 0 { for i in 0..len { if nums[i] > nums[i+1] { nums.swap(i, i+1); } } len -= 1; } } fn bubble_sort3(nums: &mut [i32]) { let mut compare = true; let mut len = nums.len() - 1;...
Rust
0
['recall'], valid_ret['ndcg'], valid_ret['precision'], valid_ret['hit_ratio']]) print(train_res) # ********************************************************* # early stopping when cur_best_pre_0 is decreasing for 10 successive steps. cur_best_pre_0, s...
Python
1
se rss::Rss; use rss::RssItem; use trigger::Trigger; use trigger::TriggerInfo; pub fn initialize_logger(should_log_debug: bool) { if (should_log_debug) { env::set_var("RUST_LOG", "debug"); } else { env::set_var("RUST_LOG", "info"); } env_logger::init(); } pub fn retrieve_xml(url: &str)...
Rust
0
tureExt}, stream::{BoxStream, StreamExt}, }; use std::cmp::min; use std::fmt; use std::future::Future; use std::time::Duration; use tokio::{sync::mpsc, time::timeout}; use tonic::codegen::{Context, Pin, Poll}; use tonic::Code; const LONG_POLLING_MAX_DURATION: Duration = Duration::from_secs(10); const LONG_POLLING_...
Rust
0
tch ns { "root" => { let strs = fill_buf(buf, &["root".as_bytes(), "*".as_bytes(), "root user".as_bytes(), "/root".as_bytes(), "/bin/sh".as_bytes()]); pwd.pw_uid = 0; pwd.pw_gid = 0; pwd.pw_name = buf[strs[0]..].as_mut_ptr() ...
Rust
0
# Quiero iterar uno a uno en todos los dias del mes for dia in range(1, 32): print("Hoy es dia", dia) # Quiero hacer una estructura if para saber si una persona es mayor de edad edad = 18 if edad >= 18: print("Eres mayor de edad") else: print("Eres menor de edad")
Python
1
sp.join(osp.dirname(__file__), 'data/model_zoo/mmcv_home') os.environ[ENV_MMCV_HOME] = mmcv_home url = _load_checkpoint('open-mmlab://train') assert url == 'url:https://localhost/train.pth' with pytest.raises(FileNotFoundError, match='train.pth can not be found.'): _load_checkpoint('open-mmlab:/...
Python
1
sum(_details[k][index]) for index in _details[k] } for k in _details: for j in range(1, len(circular_patterns[k]) + 1): count = sum([_details[k][index] >= j for index in _details[k]]) total = len(_details[k]) if j != len(cir...
Python
1
ags: u32, pub ThreadWriteFlags: u32, pub SecondaryFlags: u32, pub Anonymous1: MINIDUMP_CALLBACK_OUTPUT_0_0, pub Anonymous2: MINIDUMP_CALLBACK_OUTPUT_0_1, pub Handle: super::super::super::Foundation::HANDLE, pub Anonymous3: MINIDUMP_CALLBACK_OUTPUT_0_2, pub Anonymous4: MINIDUMP_CALLBACK_OUTPU...
Rust
0
w] <= distTo[v] + e.weight() // (ii') for all edges e = v->w on the SPT: distTo[w] == distTo[v] + e.weight() pub fn check(&self, g: &dyn IEWDigraph, s: usize) -> Result<(), String> { // has a negative cycle if let Some(cycle) = self.cycle.as_ref() { let mut weight = 0.0; ...
Rust
0
acfg1](mdacfg1) module"] pub type MDACFG1 = crate::Reg<u8, _MDACFG1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MDACFG1; #[doc = "`read()` method returns [mdacfg1::R](mdacfg1::R) reader structure"] impl crate::Readable for MDACFG1 {} #[doc = "Master Domain Assignment Configuration Register"] pub mod mdacfg1; #[...
Rust
0
rior); let mut rng = StdRng::from_seed([1; 32]); let x = start.sample(&mut rng).unwrap(); println!("{}", x); } } use dominator::{html, Dom}; pub fn render_step_3() -> Dom { html!("module-sidebar-body", { .property("slot", "body") .child( html!("sidebar-empty...
Rust
0
) -> BigInt { } } */ // AddAssign // BitAnd // BitAndAssign // BitOr // BitOrAssign // BitXor // BitXorAssign // Div // DivAssign // Mul // MulAssign // Neg // Not // Rem // RemAssign // Shl // ShlAssign // Shr // ShrAssign // Sub // SubAssign impl BigInt { fn new() -> BigInt { return BigInt { sign: ...
Rust
0
import random from ete3 import Tree, TreeStyle, NodeStyle, faces, AttrFace, TreeFace, TextFace # Tree Style used to render small trees used as leaf faces small_ts = TreeStyle() small_ts.show_leaf_name = True small_ts.scale = 10 def get_example_tree(): # Random tree t = Tree() t.populate(20, random_branche...
Python
1
from . import DefaultTable from . import ttProgram class table__f_p_g_m(DefaultTable.DefaultTable): """Font Program table The ``fpgm`` table typically contains function defintions that are used by font instructions. This Font Program is similar to the Control Value Program that is stored in the ``pre...
Python
1
values.len(), 5); assert_eq!(values[0], "id1".to_string()); assert_eq!(values[1], "id2".to_string()); assert_eq!(values[2], "class1".to_string()); assert_eq!(values[3], "class2".to_string()); assert_eq!(values[4], "class3".to_string()); } pub mod brew; pub mod deb; pub mod github; pub mod gitlab; pu...
Rust
0
okenized) if max_length and loss_starts[0] >= max_length: return None, None, None if discard_non_loss_tokens_at_tail: input_ids = input_ids[: loss_ends[-1]] if max_length: input_ids = input_ids[:max_length] loss_ends[-1] = min(max_length, loss_ends[-1]) return input_ids, ...
Python
1
#!/usr/bin/env python3 import sys sys.path.insert(0, '/root/hypothesis-llm/envs/srsly_env/lib/python3.13/site-packages') import srsly # Test msgpack with large integers print("Testing msgpack with large integers:") test_values = [ 2**63 - 1, # Max signed 64-bit int 2**63, # Just over max signed ...
Python
1
!("mooneye test failed with A = {}", regs.a); } if regs.b != 3 || regs.c != 5 || regs.d != 8 || regs.e != 13 || regs.h != 21 || regs.l != 34 { panic!("mooneye test failed regs = {:?}", regs); } } macro_rules! mooneye_tests { ($prefix: expr; $($test_name: ident $(- $suffix_name: ident)? $(for $e...
Rust
0
x += 1; } macro_rules! call { ($imm8:expr) => {{ sss = _mm_srai_epi32::<$imm8>(sss); }}; } constify_imm8!(precision, call); sss = _mm_packs_epi32(sss, sss); let pixel: u32 = transmute(_mm_cvtsi128_si32(_mm_packus_epi16(ss...
Rust
0
v.push(i); v }) .map(|item| { let mut list = LinkedList::new(); list.push_back(item); list }) .reduce(LinkedList::new, |mut list1, mut list2| { list1.append(&mut list2); ...
Rust
0
loss_mask = ((merged[i] - gt).abs().mean(1, True) > (merged_teacher - gt).abs().mean(1, True) + 0.01).float().detach() loss_distill += ((flow_teacher.detach() - flow_list[i]).abs() * loss_mask).mean() c0 = self.contextnet(img0, flow[:, :2]) c1 = self.contextnet(img1, flow[:...
Python
1
ing { match (a, b) { // Trivial equality checks. (Self::Orchard, Self::Orchard) | (Self::Sapling, Self::Sapling) | (Self::P2sh, Self::P2sh) | (Self::P2pkh, Self::P2pkh) => cmp::Ordering::Equal, // We don't know for certain the preference o...
Rust
0
self.revealed = i; break; } } } pub fn change_selection(&mut self) { for i in 0..3 { if i != self.selection && i != self.revealed { self.selection = i; break; } } } pub fn is_vict...
Rust
0
ape (n_samples, n_features) y : numpy.ndarray True labels (1 for genuine, 0 for impostor) Returns: -------- float Accuracy score )rAr)r r!r"r<s r evaluate"ManhattanFilteredDistance.evaluaters ll1o a--r)r r rr N)g?) __name__ __module__...
Python
1
KeyRegistration(Arbitrary::arbitrary(g)), 1 => CertificateContent::StakeKeyDeregistration(Arbitrary::arbitrary(g)), 2 => CertificateContent::StakeDelegation(Arbitrary::arbitrary(g)), 3 => CertificateContent::StakePoolRegistration(Arbitrary::arbitrary(g)), ...
Rust
0
import functions as f import networkx as nx #type: ignore import matplotlib.pyplot as plt #type: ignore from pregatire_test_practic.lllll.desenareGraf import desenareGraf def creareGraf(E, V) : G = nx.DiGraph() G.add_edges_from(E) G.add_nodes_from(V) return G import numpy as np #type: ignore def inchid...
Python
1
.port_name(in_port)?; let (tx, rx) = mpsc::channel(); let (midi_tx, midi_rx) = mpsc::channel(); // _conn_in needs to be a named parameter, because it needs to be kept alive until the end of the scope let _conn_in = midi_in .connect( in_port, "midir-read-input", ...
Rust
0
import sys import json from pprint import pprint import operator def hw(): print 'Hello, world!' def lines(fp): print str(len(fp.readlines())) def pri(y): print y def main(): sent_file = open(sys.argv[1]) tweet_file = open(sys.argv[2]) #hw() #lines(sent_file) #lines(tweet_fil...
Python
1
vec!['$']; // concateno tutte le sequenze for handle in &sorted_handles { let start_pos = last_index; for c in graph.sequence(*handle) { linearization.push(c as char); last_index += 1; } let last_pos = last_index - 1; // last position included in position...
Rust
0
dentifier("X_28".to_string()), BoolExpr::VarParIdentifier("X_29".to_string()), ]), Expr::Float(1.0) ], annos: vec![] } )) ); } #[test] fn test_constraint_item_4() { use crate::{BoolExpr, Expr}; ...
Rust
0
vm.validate_header(block2.header, block1.header) with pytest.raises(ValidationError, match="mix hash mismatch"): vm.validate_seal(block2.header) def test_validate_header_fails_on_invalid_parent(noproof_consensus_chain): block1 = noproof_consensus_chain.mine_block() block2 = noproof_consensus_cha...
Python
1
'''num = int(input('enter a number: ')) temp = num digit, sum = 0, 0 length = len(str(num)) for i in range(length): digit = int(temp%10) temp = temp/10 sum+=pow(digit, length) if sum == num: print('Armstrong') else: print('not an Armstrong') ''' low, high = int(input(('enter your first numbe...
Python
1
s, 0.5 / y - 1.0); self.envelope_m1 / (4.0 * PI * y * t) * f } } } pub fn comoving_mass_density(&self, r: f64, t: f64) -> f64 { self.mass_rate_per_steradian(r, t) / (self.gamma_beta(r, t) * r * r) } pub fn wind_mass_rate_per_steradian(&self) -> f64 { ...
Rust
0
import warnings from audiomentations.augmentations.air_absorption import get_temperature_humidity_key DEBUG = False from audiomentations import AirAbsorption import numpy as np import pytest import scipy import scipy.signal def get_chirp_test(sample_rate, duration): """Create a `duration` seconds chirp from 0H...
Python
1
(|visible_rect| PreCopy { image: png_image, copy_region: CopyRegion { src_offset: (visible_rect.origin - dst_rect.origin).to_point().to_u32(), dst_offset: visible_rect.origin.to_u32(), extent: visible_rect.size.to_u32(), ...
Rust
0
Create configuration from template. Args: name: Configuration name template_type: Template type Returns: BacktestConfig: Created configuration """ if template_type == 'basic': return BacktestConfig( name=name, ...
Python
1
64 to string and prevent failing fn base64_to_string(base64_string: &str) -> Result<String> { let decoded_string = &decode(base64_string)?; let result = from_utf8(decoded_string)?.to_string(); Ok(result) } // Validate signature // need to be public because its been used // by our tests in the bundler // // NOTE:...
Rust
0
key(arg) } fn pretty_print_config(&self) -> PrettyPrintConfig { PrettyPrintConfig { disabled_binops: self .params .get("disabled_binops") .and_then(|x| x.strip_prefix('[')?.strip_suffix(']')) .unwrap_or(&String::new()) ...
Rust
0
}; Self::from_seed_impl(seed) } pub fn from_seed_impl(seed: Vec<u8>) -> Result<Self, ExtendedPublicKeyErrors> { let xpriv = match ExtendedPrivateKey::from_seed_impl(seed) { Ok(v) => v, Err(e) => { return Err(ExtendedPublicKeyErrors::InvalidSeedHmacErr...
Rust
0
e image frame in pixel coordinates. /// This means the keypoint is neither undistorted nor normalized. /// /// For calibrated coordinates, use a type that implements [`Bearing`](crate::Bearing). /// This can be a type from a camera model crate (like `cv-pinhole`), or /// it can be the `Unit<Vector3<f64>>` type, which i...
Rust
0
# import json import requests class MetricProxy: def __init__(self, url="http://localhost:1337"): self.url = url def jobs(self) -> dict: return requests.get(f'{self.url}/profiles').json() def profile(self,jobid) -> dict: return requests.get(f'{self.url}/profiles/get?jobid={jobid}'...
Python
1
JsLogger::new(log), debug: JsLogger::new(debug), ghost } } pub fn repl(&mut self, input: String) -> Result<Option<String>,JsValue> { let Solomonoff { repl, log, debug,ghost } = self; repl.repl(log, debug, &input,&ghost).map_err(|e|JsValue::from(format!("{:?}",e))...
Rust
0
# # Copyright © 2020 Keith Packard <keithp@keithp.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, or # (at your option) any later version. # # This progra...
Python
1
-MONTH 9(06) 商品年月 settleMonth = line[offset:(offset + 6)] offset += 6 #FILLER X(1) "|" offset += 1 #LMAT-STRIKE-PRICE 9(06).9(03) 履約價 strikePrice = line[offset:(offset + 10)] offset += 10 #FILLER X(1) "|" ...
Python
1
Result<V::Value> { // Considered just a wrapper over the contained value visitor.visit_newtype_struct(self) } fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> { visitor.visit_seq(SeqBuilder::new(self).try_build()?) } fn deserialize_tuple<V: Visitor<'de...
Rust
0
let in_exp: f64 = (-1.0) * (x - mean).powi(2) / (2.0 * std_d); let density: f64 = (1.0_f64.exp()).powf(in_exp) / (2.0 * PI * std_d).sqrt(); density } // multi gaussian ditribution, with controable mean and standard deviation fn multi_gaussian_dist(x_v: & DVector<f64>, mean_v: & DVector<f64>, std_d_mat: & DMatr...
Rust
0
crate::otsys::otThreadGetExtendedPanId). #[must_use] fn get_extended_pan_id(&self) -> &ExtendedPanId; /// Functional equivalent of /// [`otsys::otThreadSetExtendedPanId`](crate::otsys::otThreadSetExtendedPanId). fn set_extended_pan_id(&self, xpanid: &ExtendedPanId) -> Result; /// Functional eq...
Rust
0
from django.contrib import admin from .models import Post,Author from django.forms import Textarea from django.db import models # Define the admin class for Post model class PostAdmin(admin.ModelAdmin): list_display = ('title', 'status','created_at') search_field = ('author', 'status','title') list_filter...
Python
1
rary_dirs if os.name == "nt" or sys.platform == "cygwin": # On Windows: # - DLLs get installed under `bin`. # - We need to inject later the DLL in the wheel using `data_files`. # - We do not use `runtime_library_dirs` as workaround for a # `distutils` bug (http://bugs.pytho...
Python
1
, error: null | undefined, complete: () => void): Unsubscribable; // /** @deprecated Use an observer instead of an error callback */ // subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Unsubscribable; // /** @deprecated Use an observer instead of a complete callback */ ...
Rust
0
import torch from transformers import AutoModelForCausalLM, AutoTokenizer def _load_model_tokenizer(checkpoint_path): tokenizer = AutoTokenizer.from_pretrained(checkpoint_path, resume_download=False) model = AutoModelForCausalLM.from_pretrained( checkpoint_path, torch_dtype="auto"...
Python
1
# Copyright 2017 The TensorFlow 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 applica...
Python
1
from controller.controladorInscricao import ControladorInscricao from DAOs.inscricao_dao import InscricaoDAO from view.telaInscricao import TelaInscricao class ControladorRelatorio: def __init__(self): self.__controlador_inscricao = ControladorInscricao(self) self.__inscricao_DAO = InscricaoDAO() ...
Python
1
ation L = M; } trait D { //~ ERROR missing `fn`, `type`, or `const` for associated-item declaration Z = { 2 + 3 }; } trait E { ::Y (); //~ ERROR expected one of } impl S { pub hello_method(&self) { //~ ERROR missing println!("Hello"); } } fn main() { S.hello_method(); //~ no method nam...
Rust
0
add_skill_target(ui, skill_data); add_skill_use_ability_value(ui, skill_data); add_skill_power(ui, skill_data); add_skill_steal_ability_value(ui, skill_data); add_skill_status_effects(ui, skill_data); add_skill_requirements(ui...
Rust
0
hema Fields", cls="text-green-600") ), mui.CardBody( fh.Pre( fh.Code( "\n".join( [ f"{field_name}: {repr(value)}" ...
Python
1
hw state for soft resets leds::set(0x00); heap::init(); unsafe { main(); } } #[panic_handler] fn panic_handler(panic_info: &PanicInfo) -> ! { leds::set(0xff); writeln!(stdio::stdout(), "Panic: {}", panic_info).ok(); loop { marv::sleep_cycles(100000000 / 4); leds:...
Rust
0
99, &Iso88599) | (&Iso885910, &Iso885910) | (&ShiftJis, &ShiftJis) | (&EucJp, &EucJp) | (&Iso2022Kr, &Iso2022Kr) | (&EucKr, &EucKr) | (&Iso2022Jp, &Iso2022Jp) | (&Iso2022Jp2, &Iso2022Jp2) | (&Iso88596E, &Iso88596E) | ...
Rust
0
&Error) { eprintln!("[ERROR] {}", error); } } <reponame>tailhook/rotor-stream<filename>examples/monitor.rs extern crate nix; extern crate rotor; extern crate rotor_stream; extern crate argparse; extern crate httparse; extern crate env_logger; use std::cmp::max; use std::str::from_utf8; use std::net::ToSoc...
Rust
0
contents = String::new(); file.read_to_string(&mut contents)?; Ok(mock.with_header("content-type", "application/json") .with_body(&contents) .with_status(200)) } #[test] fn get_open() { //! Ensure that we can load valid open orders // GIVEN - a valid open order in place let alpaca = block...
Rust
0
# swift_build_support/products/libdispatch.py -------------------*- python -*- # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.tx...
Python
1
EBUG_INFO { *self } } pub type LPCREATE_THREAD_DEBUG_INFO = *mut CREATE_THREAD_DEBUG_INFO; #[repr(C)] #[derive(Copy)] pub struct CREATE_PROCESS_DEBUG_INFO { pub hFile: ::HANDLE, pub hProcess: ::HANDLE, pub hThread: ::HANDLE, pub lpBaseOfImage: ::LPVOID, pub dwDebugInfoFileOffset: ::DWORD, pub nD...
Rust
0
d(model, mujoco.mjtObj.mjOBJ_BODY, "ball") ball_qvel_adr = model.body_dofadr[ball_body_id] # 자유도 인덱스 시작점 name1 = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_GEOM, g1) name2 = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_GEOM, g2) ...
Python
1
import json import re import argparse def extract_apis_from_md(md_file): """Extract Windows API function names from the .md file.""" with open(md_file, 'r', encoding='utf-8') as f: md_content = f.readlines() apis = [] for line in md_content: match = re.findall(r'\b[A-Za-z0-9_]+\b',...
Python
1
ative_path(from_path, to_path): # Convert paths to absolute for uniformity from_path = from_path.resolve() to_path = to_path.resolve() if from_path.is_file(): from_path = from_path.parent if to_path.is_file(): to_path = to_path.parent if not from_path.is_dir() or not to_path.is_d...
Python
1
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # @Author : lisztomania # @Date : 2021/1/16 # @Software : Pycharm # @Version : Python 3.8.5 # @File : Driver_Init.py # @Function : 驱动初始化 from selenium.webdriver import Chrome from selenium.webdriver.chrome.webdriver import WebDriver from inside.Options.Options i...
Python
1
from __future__ import absolute_import from __future__ import print_function import veriloggen import fsm_hook_nested expected_verilog = """ module top # ( parameter WIDTH = 8 ) ( input CLK, input RST, output [WIDTH-1:0] LED ); blinkled #( .WIDTH(WIDTH) ) inst_blinkled ( .CLK(CLK), .RS...
Python
1
ons, plot_properties=plot_properties, return_filter=return_filter) FILTER_INPUTS = { 'fir' : ['n_cycles', 'n_seconds', 'remove_edges'], 'iir' : ['butterworth_order'], } def _filter_input_checks(filter_type, filter_kwargs): """Check inputs...
Python
1
tor.lifetimes) } /// Generates a for<...> clause from a list of given lifetimes fn bound_lifetimes(lifetimes: Vec<Lifetime>) -> Option<BoundLifetimes> { if lifetimes.is_empty() { None } else { Some(BoundLifetimes { lifetimes: lifetimes.into_iter().map(LifetimeDef::new).collect(), ...
Rust
0
from odoo import api, models class ResCurrency(models.Model): _inherit = "res.currency" # TODO remove this method in master. It's not used anymore. @api.model def get_currencies_for_spreadsheet(self, currency_names): """ Returns the currency structure of provided currency names. ...
Python
1
* PI / 180 lat_b = latb * PI / 180 a = lat_a - lat_b b = loga * PI / 180 - logb * PI / 180 dis = 2 * math.asin( math.sqrt(math.pow(math.sin(a / 2), 2) + math.cos(lat_a) * math.cos(lat_b) * math.pow(math.sin(b / 2), 2))) distance = EARTH_RADIUS * dis * 1000 return distance def evaluate...
Python
1
V = V[:, pos_idx] else: V = V_raw[:, pos_idx] # 获取空间坐标 X = adata.obsm["spatial"][:, pos_idx] # 向量预处理 if normalize_v: V = V / np.quantile(np.linalg.norm(V, axis=1), normalize_v_quantile) # 3D HTML模式 (支持所有方法) if is_3d: return create_3d_ht...
Python
1
= Instant::now(); //! socket.send(Message::Item(ServerMsg::Ping)).await.ok(); //! //! if let Some(msg) = socket.recv().await { //! match msg { //! Ok(Message::Item(ClientMsg::Pong)) => { //! println!("ping: {:?}", start.elapsed()); //! }, //! Ok(_) =>...
Rust
0
ve, 0).unwrap(); assert_ok!(Democracy::vote(Origin::signed(1), r, AYE)); assert_ok!(Democracy::vote(Origin::signed(2), r, NAY)); assert_ok!(Democracy::vote(Origin::signed(3), r, NAY)); assert_ok!(Democracy::vote(Origin::signed(4), r, AYE)); assert_ok!(Democracy::vote(Origin::signed(5), r, NAY)); asser...
Rust
0
d not raise any exceptions result = reward_fn( messages=[ {"role": "user", "content": "Hello"}, {"role": "assistant", "content": large_content}, ], ground_truth=[{"role": "user", "content": "Hello"}], # Changed ) assert result...
Python
1
#!/usr/bin/env python """ Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/) See the file 'LICENSE' for copying permission """ import os import re from lib.core.common import singleTimeWarnMessage from lib.core.common import zeroDepthSearch from lib.core.compat import xrange from lib.core.enums import D...
Python
1
from constructs import Construct from aws_cdk import ( Stack, aws_route53 as route53, aws_elasticloadbalancingv2 as elbv2, aws_route53_targets as route53_targets, ) class AliasHealthcheckRecordStack(Stack): def __init__(self, scope: Construct, construct_id: str, zone: route53.HostedZone, primaryLoadB...
Python
1
_NAME) ); assert_eq!( Some("BTC/USDT".to_string()), normalize_pair("btcusdt", EXCHANGE_NAME) ); } #[test] fn verify_swap_symbols() { let markets = fetch_swap_markets_all(); for market in markets.iter() { let pair = normalize_pair(&market.symbol, EXCHANGE_NAME).unwrap(); ...
Rust
0
from geo_utils import filter_by_distance, get_state_abbrev, get_neighboring_states def filter_house(criteria, house_data): print(f"criteria received at filter_houses : {criteria}") filtered_data = house_data.copy() if 'cost' in criteria and criteria['cost'] is not None: filtered_data = filtered_d...
Python
1
le" logger.info("Obtaining %s", req) with indent_log(): if self.require_hashes: raise InstallationError( "The editable requirement {} cannot be installed when " "requiring hashes, because there is no single file to " ...
Python
1
w = self.featureTransform(self.X_train, self.shapelets) model = LogisticRegression(support_size=size) model.fit(X_train_new, self.y_train) self.index = np.nonzero(model.coef_)[0] X_test_new = self.featureTransform( self.X_test, self.shapelets, self.index) y_pred = mod...
Python
1
::runtime::Runtime; use simplelog::{TermLogger, LevelFilter, Config as LogConfig}; use std::prelude::*; use std::fs; use crate::sentry::*; use std::net::{SocketAddr, IpAddr}; use std::str::FromStr; use serde_json::json; mod sentry; use sentry::StartResult; use sentry::config::Config; /// Broadcasts one receiver to a...
Rust
0
"""Example plot showing the profile of the Wstat statistic and its connection to significance.""" import numpy as np import matplotlib.pyplot as plt from gammapy.stats import WStatCountsStatistic count_statistic = WStatCountsStatistic(n_on=13, n_off=11, alpha=0.5) excess = count_statistic.n_sig # We compute the WSta...
Python
1
return [a] * 2 e = ExecuteFunction(f, replace=ReplacingScope.LOCAL) es = ExecuteFunction(fs, default_key="test", replace=ReplacingScope.LOCAL) # test LOCAL assert e.run({"a": 0, "b": 1}) == {"a": 1} assert es.run({"a": 0}) == {"a": 0, "test": [{"a": 1}, {"a": 1}]} assert e.us...
Python
1
subset` is not within `buf`. pub(crate) fn as_range(buf: &[u8], subset: &[u8]) -> Option<std::ops::Range<usize>> { if subset.is_empty() { return None; } let subset_p = subset.as_ptr() as usize; let buf_p = buf.as_ptr() as usize; let off = match subset_p.checked_sub(buf_p) { Some(off)...
Rust
0
n get_body() -> Result<HtmlElement, E> { get_document()?.body().ok_or(E::CouldNotRetrieveDocumentBody) } pub fn get_element_by_id(id: &str) -> Result<Element, E> { get_document()?.get_element_by_id(id).ok_or(E::ElementIdIsNotFound(id.into())) } pub fn generate_empty_html_collection() -> Result<HtmlCollection, E> { ...
Rust
0
![recursion_limit = "128"] #[macro_use] extern crate diesel; #[macro_use] extern crate diesel_infer_schema; #[cfg(feature = "sqlite")] #[macro_use] extern crate diesel_migrations; extern crate dotenv; extern crate test; mod schema; use self::schema::{ comments, posts, users, Comment, NewComment, NewPost, NewUser...
Rust
0
Ok(success) => println!("Success: {:#?}", success), /// Err(e) => println!("Error: {}", e), ///} /// /// ``` /// See how to create the Heroku [`api_client`][httpApiClientConfig]. /// /// [httpApiClientConfig]: ../../../framework/struct.HttpApiClient.html /// [response]: ../struct.OAuth.html pub struct OAuthDetails<...
Rust
0
def test_hello_test(vamos): retcode, stdout, stderr = vamos.run_prog("test_hello") assert retcode == 0 assert stdout == ["VamosTest: PrintHello()"] assert stderr == [] def test_hello_mem_trace_test(vamos): retcode, stdout, stderr = vamos.run_prog("test_hello", vargs=["-t"]) assert retcode == 0...
Python
1
from django.contrib import admin from base_user.models import BaseUser # Register your models here. admin.site.register(BaseUser)
Python
1
# !/usr/bin/python3 # -*- coding: utf-8 -*- # @Author: 花菜 # @File: test_tree_service_impl.py # @Time : 2022/9/5 00:22 # @Email: lihuacai168@gmail.com from django.test import TestCase from fastrunner.dto.tree_dto import TreeUniqueIn, TreeUpdateIn from fastrunner.services.tree_service_impl import tree_service class ...
Python
1
""" Defines a custom MathJax bokeh model to render text using MathJax. """ from bokeh.models import Markup class MathJax(Markup): """ A bokeh model that renders text using MathJax. """ __javascript__ = [ "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"...
Python
1
nt_balance) to be singular, but encountered a plural expression: parts.supply_records.supplier.account_balance", id="bad_plural_i", ), pytest.param( TableCollectionInfo("nations") ** CalculateInfo( [ SubCollectionInfo("customers") ...
Python
1
, np.mean(np.square(u_pred[:, 0] - u_function(x_area[:,0], x_area[:,1])))) # print("L2 error:", np.linalg.norm(u_function(x_area[:,0], x_area[:,1]) - u_pred[:, 0])/np.linalg.norm(u_function(x_area[:,0], x_area[:,1]))) # # df1 = pd.DataFrame(np.array(model.eigenvalues_iter).T) # df2 = pd.DataFrame(np.array(model.L2)) # ...
Python
1
app, middle) = ::app(); let mut req = ::req(app.clone(), Method::Get, "/api/v1/crates/foo_owners/owners"); { let conn = app.diesel_database.get().unwrap(); ::new_user("foobar").create_or_update(&conn).unwrap(); let user = ::new_user("foo").create_or_update(&conn).unwrap(); ::sig...
Rust
0
assert!(e.to_string().contains(expected_err), "Can not find expected error '{}' while parsing '{}'. Actual error '{}'", expected_err, s, e); } } } } <gh_stars>1-10 #![cfg(feature = "dynamodbstreams")] extern crate rusoto_core; extern c...
Rust
0
(30.0..100.0).contains(&score) { QcStatus::Mediocre } else if score >= 100.0 { QcStatus::Bad } else { QcStatus::Good } } } #[derive(Clone, Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct QcResult { pub missing_data: Option<QcResultMissingData>, ...
Rust
0
), ); cpu.registers .set_flag(CpuFlag::NEGATIVE, sign(diff, insn.operand_size)); } _ => unreachable!(), }; // Signal regular PC increment to the CPU. cpu.increment_pc = true; 1 } /// Performs an additional or subtraction, based on ...
Rust
0