text
string
label_name
string
labels
int64
in pattern"), }, // TODO: Confirm that rustc introduces this pattern only for primitive derefs box PatKind::Deref { subpattern } => self.extract_pattern(subpattern, binder), _ => self.unsupported_pattern(pattern.span, "Unsupported kind of pattern"), } } fn extract_subpatterns( &m...
Rust
0
self.topology_props = props.clone(); self.topology_decoded = Some(TopologyID { socket: (self.x2apic_id & self.topology_props.socket.mask) >> self.topology_props.socket.shift, core: (self.x2apic_id & self.topology_props.core.mask) >> self.topology_props.core.shift, thread:...
Rust
0
hat const MSG_TRUNC = 0x20; // Return the real length of the packet or datagram const MSG_DONTWAIT = 0x40; // Nonblocking io const MSG_WAITALL = 0x0100; // Wait for a full request const MSG_ERRQUEUE = 0x2000; // Fetch message from error...
Rust
0
-> SEXP; pub fn CLOENV(x: SEXP) -> SEXP; pub fn RDEBUG(x: SEXP) -> ::libc::c_int; pub fn RSTEP(x: SEXP) -> ::libc::c_int; pub fn RTRACE(x: SEXP) -> ::libc::c_int; pub fn SET_RDEBUG(x: SEXP, v: ::libc::c_int) -> (); pub fn SET_RSTEP(x: SEXP, v: ::libc::c_int) -> (); pub fn SET_RTRACE(x: SEXP...
Rust
0
t_ok!(result); assert_eq!(&stdout.get_ref()[0..2], b"8\n"); } #[test] fn milestone_5_main() { let bytecode = vec![ Alloca(Type::Int32), PushInt32(0), Store(Type::Int32, 0), PushInt32(3), Alloca(Type::Int32), Store(Type:...
Rust
0
PnL по сделкам pnl_trades = [t for t in self.trades if 'pnl' in t] if pnl_trades: pnls = [t['pnl'] for t in pnl_trades] winning_trades = [p for p in pnls if p > 0] losing_trades = [p for p in pnls if p < 0] ...
Python
1
* * `needle` - The string to search for * * # Return value * * `Some` containing the byte index of the first matching substring * or `None` if there is no match */ fn find_str(&self, needle: &str) -> Option<uint> { if needle.is_empty() { Some(0) } else...
Rust
0
# -*- coding: utf-8 -*- """ dsk_metrics.py Different functions to plot DeepSurvK metrics. """ import matplotlib as mpl from matplotlib import pyplot as plt import seaborn as sns __all__ = ['plot_loss'] #%% # A few tweeks to make plots pretty. sns.set(style="whitegrid") sns.set(font_scale=1.25) sns.set_style('ticks'...
Python
1
let aligned = hdr.version == CONST_ALIGNED_FILE_VERSION; let pos = stream_len - i.len(); // Align input if aligned && hdr.num_states > 0 && pos % CONST_ARCH_ALIGNMENT > 0 { i = take(CONST_ARCH_ALIGNMENT - (pos % CONST_ARCH_ALIGNMENT))(i)?.0; } let (mut i, const_s...
Rust
0
test] fn test_d07_p1_proper() { let input = generate_input(&read_to_string("./input/2015/day7.txt").unwrap()); let result = solve_part_1(&input); assert_eq!(956, result); } #[test] fn test_d07_p2_proper() { let input = generate_input(&read_to_string("./input/2015/day7.tx...
Rust
0
{ match self.remove_inner(k, guard) { Ok(n) => return n, Err(_) => backoff.spin(), } } } #[inline] fn compute_if_present_inner<F>( &self, k: &T, remapping_function: &mut F, _guard: &Guard, ) -> Result<Optio...
Rust
0
2 ); assert_eq!( validator_1_unbond_list_before[1].amount(), &U512::from(UNDELEGATE_AMOUNT_3) ); let validator_2_unbond_list = unbond_purses_before .get(&*VALIDATOR_2) .cloned() .expect("should have unbond"); assert_eq!(validator_2_unbond_list.len(), 1); // ...
Rust
0
clippy::decimal_literal_representation, //TODO clippy::doc_markdown, clippy::empty_enum, clippy::option_expect_used, clippy::expl_impl_clone_on_copy, clippy::explicit_into_iter_loop, clippy::explicit_iter_loop, clippy::fallible_impl_from, clippy::filter_map, clippy::filter_map_next...
Rust
0
__version__ = "0.1.0" __author__ = "Your Name" __email__ = "your.email@example.com"
Python
1
'HD' else: q = 'SD' #host = re.findall('">(.+?)\.',data[0], re.DOTALL )[0] valid, host = source_utils.is_host_valid(url, hostDict) lang, info = 'es', 'LAT' sources.append( {'source': host, 'quality': q, 'language': lang, 'url': url, 'info'...
Python
1
type) test_kvstore('local_allreduce_cpu', stype) test_kvstore('local_allreduce_device', stype) ## compression for local kvstore happens only when reduce is on device test_compress_kvstore('local_allreduce_device', '1bit', -.5) test_compress_kvstore('local_allreduce_device', '1bit', 0) t...
Python
1
class Solution: def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int: m = len(matrix) n = len(matrix[0]) ans = 0 # Transfer each row of matrix to prefix sum for row in matrix: for i in range(1, n): row[i] += row[i - 1] for baseCol in range(n): for ...
Python
1
from romer_minirobot.robot import MiniRobot from romer_minirobot.modules import robot, Bool from pynput import keyboard import time # Multicast group details MULTICAST_GROUP = '224.0.0.252' MULTICAST_TOPIC_PORT = 5007 class KeyboardControl(): def __init__(self, robot, x_linear_speed, z_angular_speed): se...
Python
1
# first party from delphi.epidata.common.integration_test_base_class import DelphiTestBase class DengueNowcastTest(DelphiTestBase): """Basic integration tests for dengue_nowcast endpint.""" def localSetUp(self): create_dengue_nowcasts = """ CREATE TABLE IF NOT EXISTS `dengue_nowcasts` ( ...
Python
1
64> { let mut new_arr:Vec<i64> = Vec::new(); for _ in 0..arr.len() { let lower = search_lower(arr); new_arr.push(arr[lower]); arr.remove(lower); } return new_arr; } fn main() { let mut list: Vec<i64> = vec![24, 50, 54, 6, 9, 20, 1, 3, 80, 4]; println!("Position: {:?}", s...
Rust
0
_bindgen_ty_8::SDL_LOG_CATEGORY_RENDER; pub const SDL_LOG_CATEGORY_INPUT: _bindgen_ty_8 = _bindgen_ty_8::SDL_LOG_CATEGORY_INPUT; pub const SDL_LOG_CATEGORY_TEST: _bindgen_ty_8 = _bindgen_ty_8::SDL_LOG_CATEGORY_TEST; pub const SDL_LOG_CATEGORY_RESERVED1: _bindgen_ty_8 = _bindgen_ty_8::SDL_LOG_CATEGORY_RE...
Rust
0
in_time_range = np.logical_and(time_values >= startdate,\ time_values <= enddate).nonzero()[0] curr_ds = curr_ds.isel(time=in_time_range) if (('SNAPSHOT' in shortname) and (snapshot_interval == 'monthly')): ...
Python
1
std::str::FromStr; #[macro_use] extern crate lazy_static; #[derive(Debug, Clone, Deserialize, Recap)] #[recap(regex = r"(?x) \s* (( byr:(?P<byr>\S+) | iyr:(?P<iyr>\S+) | eyr:(?P<eyr>\S+) | hgt:(?P<hgt>\S+) | hcl:(?P<hcl>\S+) | ec...
Rust
0
in bytes. pub unsafe fn read_config_space<T: Copy>(&self, offset: usize) -> T { match self.resources { VirtioResources::Mmio { ref registers } => registers.read(0x100 + offset) } } } bitflags! { /// Indicates a reason for the device to have raised an interrupt. These values are...
Rust
0
n(final_step.column_filters[1]['value max']['filters']) == 0 assert mito.dfs[1].equals( pd.DataFrame({ 'date': ['1-1-2000'], 'value max': [1] }) ) def test_replay_edits_allows_filter_editing(): df = pd.DataFrame(data={'date': ['1-1-2000', '1-2-2000', '1-3-2000'], '...
Python
1
return alert_result.success and script_result.success except Exception as e: print(f"❌ AI analysis test failed: {e}") return False def main(): """Run all tests""" print("🧪 Backend Discard Service - Test Suite") print("=" * 50) # Test queue operations qu...
Python
1
import random def get_user_inputs(): print("Welcome to the Personalized Story Generator!") name = input("Enter your name: ") favorite_color = input("Enter your favorite color: ") favorite_animal = input("Enter your favorite animal: ") dream_job = input("Enter your dream job: ") city = input("En...
Python
1
from typing import Dict, Any from sqlalchemy import update, delete, insert from sqlalchemy.future import select from sqlalchemy.orm import Session from models.data.sqlalchemy_async_models import Attendance_Member from datetime import datetime class AttendanceRepository: def __init__(self, sess:Session): ...
Python
1
_base_ = './retinanet_r50_fpn_1x_coco.py' # learning policy lr_config = dict(step=[16, 22]) runner = dict(type='EpochBasedRunner', max_epochs=24)
Python
1
space into one space. r?rwr) r~rSrrrUrrrrr)rrs r;rzAddrlistClass.getphraselistshhTZZ(zz$((#txx/A DHH%, T]]_-DHH%,  ''(9:DHH%8  T\\$//:;hhTZZ( r<)TN)__name__ __m...
Python
1
from methods import find_maximum_graph_matching if __name__ == "__main__": V1 = ['a', 'b', 'c'] V2 = ['x', 'y', 'z'] edges = [('a', 'x'), ('b', 'x'), ('b', 'y'), ('c', 'y'), ('c', 'z')] result = find_maximum_graph_matching(V1, V2, edges) print(result)
Python
1
elf, item: T) -> List<T> { Cons(item, Box::new(self)) } /// Pop the top element of the stack. /// /// Pop the top element of the stack. Returns an /// `Option<(T,List<T>)>` containing the top element and a new /// `List<T>` with that item removed, or `None` if the stack is /// empty. /// ...
Rust
0
// Only look at MetaList style attributes `[strum(...)]` .filter_map(|meta| meta.borrow().try_metalist()) .filter(|list| list.path.is_ident(attr)) .flat_map(|list| list.expand_inner()) // Match all the properties with a given ident `[strum(serialize = "value")]` ...
Rust
0
xt(events) == AfterModelInvocationEvent(agent=agent, stop_response=None, exception=exception) # 3rd call - throttled assert next(events) == BeforeModelInvocationEvent(agent=agent) assert next(events) == AfterModelInvocationEvent(agent=agent, stop_response=None, exception=exception) # 4th call - succes...
Python
1
{ assert_invalid_attestation!(result, InvalidAttestation::EmptyAggregationBitfield) }, ); } /// Specification v0.12.1: /// /// assert target.epoch in [expected_current_epoch, previous_epoch] /// /// (tests epoch after current epoch) #[test] fn invalid_attestation_future_epoch() { ...
Rust
0
class parrent: def __init__(self): pass class child(parrent): def __init__(self): super().__init__() class child2: def __init__(self): pass print(issubclass(child,parrent)) print(issubclass(child2,parrent)) print(issubclass(parrent,child))
Python
1
_foldable=False, is_placed=False) if __name__ == "__main__": # First, from initial state, recall the physical properties of objects and available actions: # object0.is_compressible is True, actions pick, place, push are applicable # object1.is_rigid is True, actions pick, place are applicable # object2...
Python
1
_base_ = [ '../../_base_/datasets/place205/basic_sz224_4xbs64.py', '../../_base_/default_runtime.py', ] # value_neck_cfg conv1x1=dict( type="ConvNeck", in_channels=1024, hid_channels=512, out_channels=1, # MixBlock v num_layers=2, kernel_size=1, with_last_norm=False, norm_cfg=dict(type='BN'), ...
Python
1
ser_id, answer_type, answer, answer_time) VALUES (%s, %s, %s, %s, %s, %s)''', (question_id, 6, user_id, answer_type, answer, answer_time)) # Generate and insert answers for survey 7 for user_id in range(5, 201): # Generate answers for users 5 to 200 answer_ti...
Python
1
", "sigmoid", "none"]. Note that passing Python's built-in `None` will default to "softmax", so you need to pass the string "none" to disable any post-processing. Return: A dictionary or a list of dictionaries containing result. If the input is a single video, will r...
Python
1
{ &(*(::std::ptr::null::<__va_list_tag>())).fp_offset as *const _ as usize }, 4usize, concat!( "Offset of field: ", stringify!(__va_list_tag), "::", stringify!(fp_offset) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<__va_list_t...
Rust
0
s://115.com/" } self.debug_log(f"获取二维码token URL: {token_url}") token_response = requests.get(token_url, headers=token_headers, timeout=10) if not token_response.ok: error_msg = f"获取二维码token失败: {token_response.status_code} - {token_response.tex...
Python
1
elf.cmp(other)) } } impl<'b, T> Ord for Ptr<'b, T> { /// Ptr is ordered by pointer value, i.e. an arbitrary but stable and total order. fn cmp(&self, other: &Ptr<'b, T>) -> Ordering { let a = self.0 as *const _; let b = other.0 as *const _; a.cmp(&b) } } impl<'b, T> Deref for P...
Rust
0
import sys import unittest from os.path import abspath, dirname rootDir = dirname(dirname(abspath(__file__))) sys.path.insert(0, rootDir) from pyglossary.apple_utils import substituteAppleCSS class Test_substituteAppleCSS(unittest.TestCase): def test_remove(self): css = b""".test { -webkit-text-combine: horizont...
Python
1
disconnected = 0 for i, data in enumerate(train_dataloader): dense_data, node_mask = utils.to_dense( data.x, data.edge_index, data.edge_attr, data.batch ) dense_data = dense_data.mask(node_mask, collapse=True) X, E = dense_data.X, dense_data.E n_nodes = [int...
Python
1
import textwrap from chess_app.pgn_database import filter_games, load_games def test_filter_games(tmp_path): sample_pgn = textwrap.dedent( """ [Event "Test"] [Site "Test"] [Date "2020.01.01"] [Round "1"] [White "A"] [Black "B"] [Result "1-0"] ...
Python
1
supported by the CPU. static CACHE: Cache = Cache::uninitialized(); /// Feature cache with capacity for `CACHE_CAPACITY` features. /// /// Note: the last feature bit is used to represent an /// uninitialized cache. #[cfg(target_pointer_width = "64")] struct Cache(AtomicU64); #[cfg(target_pointer_width = "64")] #[cfg...
Rust
0
crop the center square from the image """ if min_size != 600: import warnings warnings.warn( f"Warning: min_size is not used in image transform, " f"setting min_size will have no effect." ) return transforms.Compose( [ ImageResize( ...
Python
1
info: &CanvasInfo, mouse: &mut MouseState, event: &Event<()>) -> bool { match event { Event::WindowEvent { event: WindowEvent::CursorMoved { position, .. }, .. } => { let (x, y): (i32, i32) = (*position).into(); mouse.virtua...
Rust
0
RANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A database-backed registry, powered by [`Diesel`](https://crates.io/crates/diesel). //! //! This module contains the [`DieselRegistry`], which provi...
Rust
0
pub fn echoerr(&self, message: impl AsRef<str>) -> Fallible<()> { self.vim()?.notify("s:Echoerr", message.as_ref()) } pub fn echowarn(&self, message: impl AsRef<str>) -> Fallible<()> { self.vim()?.notify("s:Echowarn", message.as_ref()) } pub fn cursor(&self, lnum: u64, col: u64) -> Fal...
Rust
0
the initial value y_0 in the first row. """ # Initialise the approximation array y = np.zeros([len(t), len(y_0)]) y[0] = y_0 ### Step 0: Euler h = t[1] - t[0] y[1] = y[0] + h*func(t[0], y[0], args) # Euler step ### Step 1: Adams-Bashforth, Different Stepsizes h_1 = t[1] - t[0] ...
Python
1
from opencompass.multimodal.models.llama_adapter_v2_multimodal import ( LlamaAadapterMMBenchPostProcessor, LlamaAadapterMMBenchPromptConstructor) # dataloader settings val_pipeline = [ dict(type='mmpretrain.torchvision/Resize', size=(224, 224), interpolation=3), dict(type='mmpretrain.torc...
Python
1
:, left : left + width] # add ax and image ax = plt.axes(panel["extent"]) ax.axis("off") ax.imshow(image) # note that you might get a slightly different layout with `plt.show()` # since it might use a different backend if save_name is not None: fig.savefig(save_name...
Python
1
expected_channel_switch = ChannelSwitch { channel_switch_count: CHANNEL_SWITCH_COUNT, new_channel: banjo_common::WlanChannel { primary: NEW_CHANNEL, cbw: banjo_common::ChannelBandwidth::CBW160, secondary80: 0, }, pause_tran...
Rust
0
DeserializationError, }; use sqlx::{ postgres::Postgres, Pool, }; use tonic::{ transport::Server, Request, Response, Status, }; use uuid::Uuid; use crate::OrganizationManagementServiceConfig; #[derive(thiserror::Error, Debug)] pub enum OrganizationManagementServiceError { #[error("Sql {0}"...
Rust
0
warn!("setsockopt is unimplemented"); Ok(0) } /// missing documentation fn ioctl(&self, _request: usize, _arg1: usize, _arg2: usize, _arg3: usize) -> SysResult { warn!("ioctl is unimplemented for this socket"); Ok(0) } /// missing documentation fn fcntl(&self, _c...
Rust
0
d = data.shape[0] # Total number of time-steps to output t = history.shape[1] if delay > 0: for step in range(n_steps): q = n_steps - 1 - step # nth block is original shifted left by n*delay steps history[step * d : (step + 1) * d] = data[:, q * delay : q * de...
Python
1
end}") periods = validate_periods(periods) if freq is not None and not is_number(freq): try: freq = to_offset(freq) except ValueError as err: raise ValueError( f"freq must be numeric or convertible to DateOffset, got {freq}" ) from err #...
Python
1
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
Python
1
Cs||_tj||dS(N(tmessaget Exceptiont__init__(Rtmsg((s"D:\Python27_64\lib\ConfigParser.pyRs cCs|jS(N(R(R((s"D:\Python27_64\lib\ConfigParser.pyt__repr__s( t__name...
Python
1
numProblems, numSolved = map(int, input().split()) d = {} for i in range(1,numProblems+1): d[i] = 0 for _ in range(numSolved): team, problem = map(int, input().split()) d[problem] += 1 print(min(d.values()))
Python
1
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #![cfg_attr(target_vendor = "uwp", windows_subsystem = "windows")]...
Rust
0
et_stroke.set('y1', '0%') target_stroke.set('x2', '100%') target_stroke.set('y2', '100%') # 更新颜色 target_stops = target_stroke.findall('.//svg:stop', namespaces) stroke_colors = stroke_gradient['colors'] if len(target_stops) == len(stro...
Python
1
other threads // that are modifying the refcount with Release, i.e. to ensure that // their writes to memory guarded by this refcount are flushed. However, // we know that threads only modify the contents of the Arc when they // observe the refcount to be 1, and no other thread could ob...
Rust
0
in: None, } } } <reponame>zachrwolfe/syn use crate::punctuated::Punctuated; use super::*; ast_struct! { pub struct PartialBorrow { pub mutability: Option<Token![mut]>, pub ident: Ident, } } ast_struct! { pub struct PartialBorrows { pub brace_token: token::Brace, ...
Rust
0
ile '--default-mapping-file', TESTING_MTMT_DEFAULT_VALID_MAPPING_FILENAME, # and a valid project name '--project-name', "project-name", # and a valid project id '--project-id', "project-id", # and a valid output file n...
Python
1
# src/difficulty_adjuster.py class DifficultyAdjuster: def __init__(self, metrics_tracker, base_difficulty=1): self.metrics_tracker = metrics_tracker self.difficulty_level = base_difficulty # Starting difficulty level def adjust_difficulty(self): """Adjusts difficulty based on player ...
Python
1
type InvitationNotifyType: str :param _JumpUrl: 回跳地址,为认证成功后页面进行回跳的URL,请确保回跳地址的可用性。注:`只有在员工邀请方式(InvitationNotifyType参数)为H5场景下才生效, 其他方式下设置无效。` :type JumpUrl: str :param _Endpoint: 要跳转的链接类型<ul><li> **HTTP**:跳转电子签小程序的http_url, 短信通知或者H5跳转适合此类型 ,此时返回长链 (默认类型)</li><li>**HTTP_SHORT_URL**:跳转电子签小程序的http_...
Python
1
pub const DISP_ROW_NUM: usize = 5; const KEY_WIDTH: usize = 7; const KEY_WIDTH_WIDE: usize = 9; const KEY_FUNC_WIDTH: usize = 9; const KEY_FUNC_WIDTH_WIDE: usize = 14; pub fn new() -> Self { Help { ..Help::default() } } pub fn disp_toggle(term: &mut Terminal) { t...
Rust
0
to_base64()?.into_bytes() }; let _ = io::stdout().write_all(&encoded); Ok(()) } pub fn main() { let opts: Opts = Opts::parse(); let _ = handle_command(&opts.subcmd).unwrap(); } extern crate sdl2; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use std::time::{Duratio...
Rust
0
{ base_currency: Decimal("10"), quote_currency: Decimal("-550000"), } ), # Sell market. Rounding takes place. 250.075 should be available, which should get truncated to 250.07. ( MarketOrder(uuid4().hex, OrderOperation.SELL, pair, Decimal("250.07")), (Decimal(...
Python
1
t50_v2 self.resnet = preActResNet50() # define smpl self.smpl = SMPL(pkl_path=smpl_pkl_path) self.feature_dim = feature_dim self.theta_dim = theta_dim self.regressor = ThetaRegressor(feature_dim + theta_dim, theta_dim, iterations) self.iterations = iterations ...
Python
1
cmd.flush_stdin(); } } Event::Window { win_event: WindowEvent::Resized(_, _), .. } | Event::Window { win_event: WindowEvent::FocusGained, .. } => { // This is needed because for some strange reason // ...
Rust
0
[test] fn test_serialize_response_channels() { let message = crate::message::MessageType::ResponseChannels { channels: vec![String::from("Channel")], }; let message = serde_json::to_string(&message) .expect("Serde failed to serialize MessageType::ResponseChannels"); ...
Rust
0
vec![ Spans::from(vec![ style_detail(&self.theme, &Detail::Author), Span::styled( Cow::from(format!( "{} <{}>", data.author.name, data.author.email )), self.theme.text(true, false), ), ]), Spans::from(vec![ style_detail(&self.theme, &Detail::Date), Span::styled( ...
Rust
0
import _plotly_utils.basevalidators class CurrentvalueValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__( self, plotly_name="currentvalue", parent_name="layout.slider", **kwargs ): super(CurrentvalueValidator, self).__init__( plotly_name=plotly_name, ...
Python
1
poname>thisconnect/bitbox02-firmware<gh_stars>1-10 // Copyright 2019 Shift Cryptosecurity AG // // 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/LICE...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import os sys.path.append("../lunar_tools/") sys.path.append(os.path.join(os.getcwd(), 'lunar_tools')) import unittest from unittest.mock import patch, MagicMock from image_gen import Dalle3ImageGenerator from image_gen import SDXL_LCM from utils import read_ap...
Python
1
# Atividade 06: # Soma de Números Positivos: # Escreva um programa que solicite números ao usuário até # que ele digite um número negativo, somando apenas os # números positivos inseridos. cont = 0 num = 0 while num != 10: num = int(input("Enter a number: ")) cont = cont + 1 if cont == 3: print('per...
Python
1
import sys import wrapt class ModelInstanceWrapper(wrapt.ObjectProxy): _fields = {} def __init__(self, model_instance): super(ModelInstanceWrapper, self).__init__(model_instance) self._fields = {f.name: 0 for f in model_instance._meta.fields} def __getattr__(self, name): if nam...
Python
1
sage_type = _VEHICLETRACKS _SCENE.fields_by_name['past_pedestrian_tracks'].message_type = _PEDESTRIANTRACKS _SCENE.fields_by_name['past_ego_track'].message_type = _VEHICLETRACK _SCENE.fields_by_name['future_vehicle_tracks'].message_type = _VEHICLETRACKS _SCENE.fields_by_name['future_pedestrian_tracks'].message_type = _...
Python
1
pplication/vnd.oasis.opendocument.spreadsheet' ] return self.mime_type in spreadsheet_mime_types def can_preview(self): """Check if file can be previewed in browser""" previewable_types = [ 'image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp', 'image/svg...
Python
1
no matter what details emerge about" " his previous mental health struggles, there's more to the story, said Brian Russell, a forensic" ' psychologist. "Psychology can explain why somebody would turn rage inward on themselves about the' " fact that maybe they weren't goi...
Python
1
from numpy import random from IndividuoFactory import IndividuoFactory class FGA: def executar(nPop: int, nGeracoes: int, nElite: int, indFact: IndividuoFactory): # criando a população inicial com genes aleatorios popInicial = [indFact.get_individuo() for _ in range(nPop)] for g in range...
Python
1
import unittest import lxml.etree from flask import request from A_cwe611_0 import app class TestCWE611_0(unittest.TestCase): def setUp(self): self.app = app.test_client() self.app.testing = True def test_correctness(self): input_xml = '<root><element>Test Data</element></root>' ...
Python
1
hdfs"; /// scheme for HDFS Federation File System pub static VIEWFS_SCHEME: &str = "viewfs"; /// Hadoop File. #[derive(Clone, Debug)] pub struct HadoopFile { inner: HdfsFile, } unsafe impl Send for HadoopFile {} unsafe impl Sync for HadoopFile {} impl Read for HadoopFile { fn read(&mut self, buf: &mut [u8])...
Rust
0
if 'jpeg' in content_type or 'jpg' in content_type: filename += '.jpg' elif 'png' in content_type: filename += '.png' elif 'webp' in content_type: filename += '.webp' else: ...
Python
1
r formatting self.stdout.write( self.style.SUCCESS(f"\n=== BATCH {batch_num} COMPLETE ===") ) self.stdout.write( self.style.SUCCESS( f"Batch {batch_num}: {stats['total']} records " f"(...
Python
1
ation = generate_anterior_mask(post_seg_array) pre_seg_img = sitk.ReadImage(str(pre_file_path)) pre_seg_array = sitk.GetArrayFromImage(pre_seg_img) pre_mask, pre_segmentation = generate_anterior_mask(pre_seg_array) # file process:Pid post_relative_path = post_file_path.relative_t...
Python
1
pub dwFlags: u32, pub szDevice: [u16; 32], pub szDescription: [u16; 256], pub liDriverVersion: i64, pub dwVendorId: u32, pub dwDeviceId: u32, pub dwSubSysId: u32, pub dwRevision: u32, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy f...
Rust
0
; let conn = DB.get()?; diesel::insert_into(bans::table) .values(( bans::user_id.eq(user_id), bans::guild_id.eq(guild_id), bans::start_time.eq(SystemTime::now()), bans::end_time.eq(SystemTime::now() .checked_add(Duration::new(hours * HOUR, ...
Rust
0
from django.contrib.admin import site from graphql_jwt.refresh_token import admin from graphql_jwt.refresh_token.utils import get_refresh_token_model from graphql_jwt.shortcuts import create_refresh_token from ..testcases import TestCase class AdminTestCase(TestCase): def setUp(self): super().setUp() ...
Python
1
from Falcom.ED62.Parser.datatable import * entries = [ NameTableData( chrId = 0x0000, word_02 = 0x0000, walkCH = 'ED6_DT27/CH03000._CH', runCH = 'ED6_DT27/CH03001._CH', walkCP = 'ED6_DT27/CH03000P._CP', runCP = 'ED6_DT27/CH03001P._CP', ms1 = 'ED6_...
Python
1
ash", "risk": "High", "params": ["amount (optional)"], "consequences": "Pay double the amount as fine and go to jail if caught" }, { "id": "tax_evasion", "name"...
Python
1
#![feature(const_fn_trait_bound)] #![feature(maybe_uninit_extra)] #![feature(allocator_api)] #![feature(c_unwind)] #![feature(step_trait)] #![warn( missing_docs, rust_2018_idioms, missing_debug_implementations, rustdoc::broken_intra_doc_links )] extern crate static_assertions as sa; use fimo_core_interf...
Rust
0
. Provided for convenience. """ return codecs.open(filename, 'r', 'utf8').read() def template(self, filename, filter=None): """ Open a template file Uses the jinja2 template engine. The following additional filters are included: modm.wordwrap(with) -- like the original filter, but with correct ...
Python
1
Trans, sign, Input, Output, gen_rand_signtx}; use crate::mempool::Mempool; use rand::Rng; use crate::crypto::merkle::MerkleTree; use crate::block::{Block, Header, Content}; use std::time::{SystemTime, UNIX_EPOCH, Instant}; use crate::crypto::hash::{Hashable, generate_rand_hash256, H160, H256}; use std::sync::{Arc, Mute...
Rust
0
GER, TextureFormat::BGRInt => glow::BGR_INTEGER, TextureFormat::RGBAInt => glow::RGBA_INTEGER, TextureFormat::BGRAInt => glow::BGRA_INTEGER, }, glow::UNSIGNED_BYTE, None, ); let texture_id = Rc::new(texture_id); ...
Rust
0
} pub fn is_sorted(&self) -> bool { let p = self.primary; let s = self.secondary; (p.index, p.prefer_next_row) <= (s.index, s.prefer_next_row) } /// returns the two ends ordered pub fn sorted(&self) -> [CCursor; 2] { if self.is_sorted() { [self.primary, self...
Rust
0