text
string
label_name
string
labels
int64
class Solution(object): def findContentChildren(self, g, s): """ :type g: List[int] :type s: List[int] :rtype: int """ g.sort(key=lambda x: -x) s.sort(key=lambda x: -x) sum = 0 childIndex = 0 for cake in s: for i in range(c...
Python
1
rn", QAS_EDIT_REPLACE: "replace" } field_name = field_mapping.get(current_state) if field_name: context.user_data["qas_edit_data"][field_name] = input_value # 回到字段选择界面 return await qas_show_edit_menu(update, context, session, user) async def qas_show_edit_menu(update: Update, con...
Python
1
"""Database utility functions.""" import re from typing import Optional def is_valid_git_diff(diff: Optional[str]) -> bool: """Validate if a string is a valid git diff. Checks for: - Basic git diff format markers - Proper structure - Not just random text Args: diff: The string to va...
Python
1
if tier_key in regalia_data["data"]["RANKED_TFT"]: rank_image = regalia_data["data"]["RANKED_TFT"][tier_key]["image"]["full"] rank_image_url = f"https://ddragon.leagueoflegends.com/cdn/{self.latest_version}/img/tft-regalia/{rank_image}" embed_color = rank_colors.get(tier_ke...
Python
1
path} } pub fn root(&self) -> Num<P::Fr> { return self.cell(constants::HEIGHT - constants::OUTPLUSONELOG, 0) } } pub struct State<P:PoolParams> { pub hashes:Vec<Vec<Num<P::Fr>>>, pub items:Vec<(Account<P::Fr>, Note<P::Fr>)>, pub default_hashes:Vec<Num<P::Fr>>, pub sigma:Num<P::Fs>...
Rust
0
}); // Create pipeline let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("NoiseRenderer pipeline layout"), bind_group_layouts: &[&bind_group_layout], push_constant_ranges: &[], }); let render_pipeline =...
Rust
0
_mut(), |x| x.as_mut_c_ptr()), size, )?; Ok((PipeHandle::new(read_pipe), PipeHandle::new(write_pipe))) } } bitflags::bitflags! { pub struct OpenModes : u32 { const PIPE_ACCESS_DUPLEX = winapi::um::winbase::PIPE_ACCESS_DUPLEX; const PIPE_ACCESS_INBOUND = winapi::um...
Rust
0
set the GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true". Args: protobuf_path: The path to the .proto file on the filesystem. This path must be resolvable from an entry on sys.path and so must all of its transitive dependencies. Returns: A module object corresp...
Python
1
_int) as libc::c_ulong) as *mut libc::c_char } if buf.is_null() { return 0 as *mut libc::c_char; } crate::src::md5::md5::MD5Final(digest.as_mut_ptr(), ctx); i = 0 as libc::c_int; while i < LENGTH { *buf.offset((i + i) as isize) = hex[(digest[i as usize] as...
Rust
0
path) { Err(e) => { println!("Error reading file size for {:?}: {}", path, e); return 0; } Ok(m) => m, }; if m.is_file() { m.len() } else if m.is_dir() { WalkDir::new(path) .into_iter() .filter_map(|e| e.ok() ...
Rust
0
Error while pluralising line '{}': '{}' is not a number", input, &function.value)); let plural_case = cardinal_rules.select(value).unwrap(); get_plural_case_str(plural_case) } FormatFunctionKind::Ordinal => { let value: f64 = function.value.parse()...
Rust
0
ap_unchecked() }; port = value.parse::<u16>()?; } _ => {} } } let addr: SocketAddr = (host, port).into(); let database = Arc::new({ let mut db = Database::open()?; trace!("with {} stories", db.index().stories.len().bright_purple(),); ...
Rust
0
ified_games.add(name) time.sleep(0.1) # Stagger notifications else: print(f"Warning: Game '{name}' not found in shortcuts dictionary.") print("All finished, Scanner was successful!") else: print("No new shortcuts were added.") print("All finished, Scanner wa...
Python
1
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ if not nums: return [] candidate1, candidate2 = None,None count1,count2 = 0,0 for i in nums: if i==candidate1: ...
Python
1
import setuptools from setuptools.extension import Extension import sys # When python -m build runs, sys.path contains a minimum of entries. I add the current directory # to it (which is guaranteed by setuptools to be the project's root) so that I can import my # build_support tools. sys.path.append('.') import build_...
Python
1
class Solution: def minimumAverage(self, nums: List[int]) -> float: nums.sort() return min((nums[i] + nums[-i - 1] for i in range(len(nums) // 2))) / 2
Python
1
}; let projection_loc = unsafe { gl.get_uniform_location(box_program.prog(), "projection") }; let color_loc = unsafe { gl.get_uniform_location(box_program.prog(), "shape_color") }; let world_to_local_loc = unsafe { gl.get_uniform_location(box_program.prog(), "world_to_local") }; ...
Rust
0
crate) fn simd_and<T>(x: T, y: T) -> T; /// or pub(crate) fn simd_or<T>(x: T, y: T) -> T; /// xor pub(crate) fn simd_xor<T>(x: T, y: T) -> T; } // Copyright © 2018 winapi-rs developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> o...
Rust
0
-ru. If no value is passed, the current datetime string will be used." ), ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate args, rest = parser.parse_known_args() parsed_args = parse_numeric_n_bool_cl_kwargs(rest) if parsed_args and verbose: ...
Python
1
raise TypeError(f"不能对浮点数进行按位运算({other_num} 和 {self})") other_num = int(other_num) elif isinstance(other_num, float) and not other_num.is_integer(): raise TypeError(f"不能对浮点数进行按位运算({other_num} 和 {self})") return other_num.__or__(int(self)) def __rxor__(self, oth...
Python
1
reads filename_with_ext = f"{filename}.{('xlsx' if fmt=='excel' else fmt)}" old_news = load_old_news(filename_with_ext, fmt) scraped_urls = {news["URL"] for news in old_news} news_results = [] workers = min(max_threads, len(cat_paths)) with ThreadPoolExecutor(max_workers=workers) as executor: ...
Python
1
etAddrsListenResult, JsonRpcError> { let (tx, rx) = oneshot::channel(); let req = NetworkMessage::JSONRPCRequest { method: NetRPCMethods::NetAddrsListen(tx), }; data.network_send.send(req).await?; let (id, addrs) = rx.await?; Ok(AddrInfo { id: id.to_string(), addrs, }...
Rust
0
; } if matches.is_present("eval") { flags.eval = true; } flags } } static ENV_VARIABLES_HELP: &str = "ENVIRONMENT VARIABLES: DENO_DIR Set deno's base directory NO_COLOR Set to disable color"; fn create_cli_app<'a, 'b>() -> App<'a, 'b> { App::new("deno") .bin_name("...
Rust
0
ut response: hdbconnect::HdbResponse = connection.statement("call GET_PROCEDURES_SECRETLY()")?; response.reverse(); for ret_val in response { match ret_val { HdbReturnValue::ResultSet(rs) => debug!("Got a resultset: {:?}", rs), HdbReturnValue::AffectedRows(affected_rows) ...
Rust
0
self._input_size, self.S, device=weights.device) # iterate through all input-output field representations pairs for io_pair in self._representations_pairs: # retrieve the indices in_indices = getattr(self, f"in_indices_{io_pair}") ...
Python
1
trix()) shader.uniform_int("image", 0) shader.uniform_float("color", color) result = (batch, shader, color) batch.draw(shader) inst.clear() return result def glVertex2f(x, y): inst = InternalData.get_instance() inst.add_vert([x, y]) inst.set_dims(2) def glVertex3f(x, y, z): ...
Python
1
.await?; } Commands::Job { id, task } => { match &task { Tasks::Status {} => { client.status(id).await?; } Tasks::Delete {} => { client.delete(id).await?; } Tasks::Upload {...
Rust
0
self.offset = 0; } #[cfg(feature = "log")] log::debug!("Time offset adjusted to {} seconds", self.offset); }; } /// Get the median network time offset. pub fn offset(&self) -> TimeOffset { self.offset } /// Get the network-adjusted time gi...
Rust
0
eturn is_known_divisible(value.owner.operands[0], divisor, max_depth - 1) case arith.ConstantOp(): return ir.IntegerAttr(def_op.value).value % divisor == 0 case arith.MulIOp(): # Only cover the case where one operand is divisible. It's still possible # that the final product is divisible, but ...
Python
1
print("Welcome to my computer Quiz!") playing = input("Do you want To play? ") if playing.lower() != "yes": print("Ok Thank you! ") quit() print("Ok lat's play :) ") score = 0 Answer = input("1. What does CPU stand for? ") if Answer.lower() == "central processing unit": score += 1 print("Correct!")...
Python
1
from_basic(signature) to convert /// from the bytes of a signature to a CspSignature pub struct SigConverter { target_algorithm: AlgorithmId, } extern crate serde_codegen; use std::path::Path; fn main() { let src = Path::new("src/serde_types.in.rs"); let dst = Path::new("src/serde_types.rs"); serde_co...
Rust
0
harvest, move_to, repairer, upgrader, withdraw_energy, CreepState, LOADING, TARGET, TASK, }; use crate::prelude::*; use num::FromPrimitive; use screeps::{ constants::find, game::get_object_typed, objects::ConstructionSite, prelude::*, ReturnCode, }; #[derive(Debug, Clone, Copy, FromPrimitive, ToPrimitive)] #[repr(...
Rust
0
; use super::piece::{MinimumPosition, Position, Positionable, Translatable, Transformable, Normalizable, Piece}; use super::pieces::Bag; /// Region to be packed. #[derive(Debug, PartialEq, Eq, Hash)] pub struct Target<T> { collection: Vec<Position<T>>, } impl<T> Target<T> where T: PartialOrd + Ord + PartialEq + E...
Rust
0
CF | Opcode::SWAPF => &color::Fg(&color::LightYellow), Opcode::INFSNZ | Opcode::DCFSNZ | Opcode::DECFSZ | Opcode::INCFSZ | Opcode::SUBWFB | Opcode::SUBWF | Opcode::DECF | Opcode::ADDWF | Opcode::ADDWFC | Opcode::INCF | Opco...
Rust
0
use prisma_models::{ModelRef, PrismaValue, RelationFieldRef}; use std::convert::TryInto; /// Handles nested disconnect cases. /// /// The resulting graph can take multiple forms, based on the relation type to the parent model. /// Information on the graph shapes can be found on the individual handlers. pub fn connect_...
Rust
0
(Copy, Clone, Debug, PartialEq, PartialOrd)] #[repr(u32)] pub enum MemberFunctionKind { Unknown = 0, Constructor = 1, Destructor = 2, InstanceMethod = 3, StaticMethod = 4, } #[derive(Copy, Clone, Debug, PartialEq, PartialOrd)] #[repr(u32)] pub enum MatchType { Normal = 0, Regex = 1, Star...
Rust
0
_event.updated_axes |= WLR_TABLET_TOOL_AXIS_WHEEL as libc::c_int as libc::c_uint; wlr_event.wheel_delta = libinput_event_tablet_tool_get_wheel_delta(tevent) } wlr_signal_emit_safe(&mut (*(*wlr_dev).c2rust_unnamed.tablet).events.axis, &mut wlr_event as *mu...
Rust
0
f os.path.exists(input_data.batch_results_folder_path): # shutil.rmtree(input_data.batch_results_folder_path) # os.makedirs(input_data.batch_results_folder_path, exist_ok=True) if input_data.multi_treading: # Pass scored_results_path into parallel_execute all_stats_df = parallel_execute...
Python
1
&scan_cmd, &self.device_info); self.current = ScanState::ScanningToDiscover { cmd: scan_cmd, mlme_txn_id: self.last_mlme_txn_id, bss_map: HashMap::new(), }; request }) } } fn maybe_insert_bss( bss_map: &mut HashMap<Bss...
Rust
0
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: cakelab/arflow_grpc/v1/delete_session_response.proto # Protobuf Python Version: 5.28.3 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.pro...
Python
1
dropzone_pose_picked = write_motor_poses(0, 0, 0, 0, 0) if dropzone_pose_picked: esp_pose_picked = write_motor_poses(0, 0, 0, 0, 0) if esp_pose_picked: results = perform_o...
Python
1
le') # Assay doesn't understand skipping tests yet; just pass # for now if Pandas cannot be imported. return assert len(df) == 1 row = df.iloc[0] assert abs(row.ra_degrees - 000.00091185) < 1e-30 assert abs(row.dec_degrees - +01.08901332) < 1e-30 star_text = b"""\ # star names b...
Python
1
== 1 { None } else { let new_tree_hash = field_tree_hash_by_index(self, i); if leaf.as_bytes() != &new_tree_hash[..] { leaf.assign_from_slice(&new_tree_hash); Some(i) } else {...
Rust
0
from flask import request from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField from wtforms.validators import ValidationError, DataRequired, Length import sqlalchemy as sa from flask_babel import _, lazy_gettext as _l from app import db from app.models import User class EditProf...
Python
1
ta" lang1_in_file = config_aligner["source_inp_file"] if config_aligner["source_inp_file"] else lang1_code + "-to-" + lang2_code + "-input_lang1" lang2_in_file = config_aligner["target_inp_file"] if config_aligner["target_inp_file"] else lang1_code + "-to-" + lang2_code + "-input_lang2" lang1_op_file = conf...
Python
1
SecondAverage, ThreeSecondAverage, ToDestination, ToGo, ToNext, Total, Zone1, Zone2, Zone3, Zone4, Zone5, Zone6, Zone7, Zone8, Zone9, UnknownValue(u64), } impl From<FieldContent> for ExdQualifiers { fn from(field: FieldContent) -> Self { if let Fi...
Rust
0
_DF_IMAGE_S16</tt> format."] #[doc = " \\param [in] grad_y The input y image. This must be in <tt>\\ref VX_DF_IMAGE_S16</tt> format."] #[doc = " \\param [out] mag The magnitude image. This is in <tt>\\ref VX_DF_IMAGE_S16</tt> format. Must have the same dimensions as the input image."] #[doc = " \\see <tt>VX...
Rust
0
A 56 bit hash value for SHA512 should be an error" ) } } <filename>tests/web.rs //! Test suite for the Web and headless browsers. #![cfg(target_arch = "wasm32")] extern crate wasm_bindgen_test; use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] fn pass() { a...
Rust
0
"instType": "SWAP" } ], } subscribe_positions_request = WSJSONRequest(positions_payload) orders_payload = { "op": "subscribe", "args": [ { "channel"...
Python
1
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if not root: return None if root.val == val: return root if root.val > val: return self.searchBST(root.left, val) return self.searchBST(root.right, val)
Python
1
"text": [ { "role": "system", "content": SYSTEM_ROLE_PROMPT }, { "role": "user", "content": f"{DEBUGGER_ANALYZE_PROMPT}\n\n{file_content}" ...
Python
1
# services/task_service.py import json import uuid from fastapi import HTTPException, UploadFile from fastapi.responses import JSONResponse from sqlalchemy.ext.asyncio import AsyncSession from src.models.task import Task from src.repositories.task_repository import create_task from src.repositories.task_repository im...
Python
1
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time import logging class LoginTester: def __init__(self, driver, logger): self.driver = driver self.logger = logger def t...
Python
1
eway_retry_max: jitter = random.randint(10, 100) * 0.01 # noqa: S311 retry_interval = ( min( GatewayClient.instance().gateway_retry_interval * (2**self.retry), GatewayClient.instance().gateway_retry_interval_max, ) ...
Python
1
#[doc = "*Required features: 'Win32_Media_DirectShow'*"] pub type TunerInputType = i32; #[doc = "*Required features: 'Win32_Media_DirectShow'*"] pub const TunerInputCable: TunerInputType = 0i32; #[doc = "*Required features: 'Win32_Media_DirectShow'*"] pub const TunerInputAntenna: TunerInputType = 1i32; pub const TunerM...
Rust
0
are different") if opt.render_to: for d in detections: cv2.rectangle(custom_image_bgr, (int(d.box.left()), int(d.box.top())), (int(d.box.right()), int(d.box.bottom())), (0, 255, 0), 2) if vwr: vwr.write(custom_image_...
Python
1
import os import csv from datetime import date import argparse def parse(): parser = argparse.ArgumentParser(description='Create WSI file list (csv format) for patch generation.') parser.add_argument('--data_folder', type=str, required=True, help='Root directory path containing WSI files') parser.add_arg...
Python
1
: qs = resolve_gift_card_tags(info) qs = filter_connection_queryset( qs, data, allow_replica=info.context.allow_replica ) return create_connection_slice(qs, info, data, GiftCardTagCountableConnection) class GiftCardMutations(graphene.ObjectType): gift_card_activate = Gi...
Python
1
"""Add ID to harvester cron Revision ID: 1be84ecb0e36 Revises: 861750430061 Create Date: 2022-07-20 17:37:18.125973 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '1be84ecb0e36' down_revision = '861750430061' branch_labels ...
Python
1
kward compatibility).""" get_hint_system().hint_bridge.store_hint(hint, category) if __name__ == "__main__": # Test the unified hint system system = get_hint_system() # Test post-action hints post_hints = system.generate_post_action_hints( 'manage_task', {'action': 'create', 'titl...
Python
1
write!(f, "{}", &self.to_str_radix(10)) } } impl fmt::Debug for Int256 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Int256({})", self.to_string()) } } impl Serialize for Int256 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serial...
Rust
0
draw_arrays(&self, mode: Primitives, count: usize) { js! { (@{self.as_reference()}).drawArrays(@{mode as i32},0,@{count as i32}); }; } pub fn pixel_storei(&self, storage: PixelStorageMode, value: i32) { js!{ (@{self.as_reference()}).pixelStorei(@{storage as i32}...
Rust
0
s opposed to the Sherlock 65-Holmeses, success in the province of detective work must always 129:be, to a very large extent, the result of luck. <NAME> 193-can extract a clew from a wisp of straw or a flake of cigar ash; 258-but <NAME> has to have it taken out for him and dusted, 321-and exhibited clearly, with a label...
Rust
0
= T1::read(read, settings)?; let v2 = T2::read(read, settings)?; let v3 = T3::read(read, settings)?; let v4 = T4::read(read, settings)?; let v5 = T5::read(read, settings)?; let v6 = T6::read(read, settings)?; let v7 = T7::read(read, settings)?; Ok((v0, v1, v2, v3...
Rust
0
0,3,6"), "436"); } #[test] fn part2_test1() { assert_eq!(Day15{}.part2("0,3,6"), "175594"); } } <gh_stars>1-10 // Std use std::collections::hash_map::{Entry, Iter}; use std::ffi::OsStr; use std::ops::Deref; use std::mem; // Internal use args::{ArgMatches, MatchedArg, SubCommand}; use args::Any...
Rust
0
to perform the grouping for a given summary request. #[derive(Serialize, Deserialize, Clone, Debug)] pub enum FieldDataType { #[serde(rename = "checkbox")] Checkbox, #[serde(rename = "currency")] Currency, #[serde(rename = "date")] Date, #[serde(rename = "date_time")] DateTime, #[se...
Rust
0
4) } #[doc = "GPIO Port 5"] #[inline] pub fn gpio_port_5(self) -> &'a mut W { self.variant(PORTSEL7W::GPIO_PORT_5) } #[doc = "GPIO Port 6"] #[inline] pub fn gpio_port_6(self) -> &'a mut W { self.variant(PORTSEL7W::GPIO_PORT_6) } #[doc = "GPIO Port 7"] #[inline...
Rust
0
.abort_handle.abort(); } } //! Run skopeo as a subprocess to fetch container images. //! //! This allows fetching a container image manifest and layers in a streaming fashion. //! //! More information: <https://github.com/containers/skopeo/pull/1476> use anyhow::{anyhow, Context, Result}; use futures_util::{Future...
Rust
0
import os import sys import time os.system('cls||clear') area = 0.0 base = 0 altura = 0 base = int(input('Entre com o valor da base: ')) altura = int(input('Entre com o valor da altura: ')) area = base * altura / 2 print('A area é:', area) time.sleep(5) sys.exit
Python
1
overflow since trying to allocate // `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add // an extra guard for this in case we're running on a platform which can use // all 4GB in user-space, e.g., PAE or x32. #[inline] fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> { if m...
Rust
0
use std::collections::BinaryHeap; impl Solution { pub fn get_least_numbers(arr: Vec<i32>, k: i32) -> Vec<i32> { let mut heap = BinaryHeap::with_capacity(k as usize); for num in arr { if heap.len() < k as usize { heap.push(num); } else { if !heap.is_empty() && *heap.peek().unwrap(...
Rust
0
let ret = self.values[self.pos]; self.pos += 1; ret } fn has_next(&self) -> bool { self.pos < self.values.len() } } fn main() { let lst = vec![ NestedInteger::List(vec![NestedInteger::Int(1), NestedInteger::Int(1)]), NestedInteger::Int(2), NestedI...
Rust
0
THE POSSIBILITY OF SUCH DAMAGE. //! The implementations of `Rand` for the built-in types. use std::char; use std::mem; use crate::{Rand,Rng}; impl Rand for isize { #[inline] fn rand<R: Rng>(rng: &mut R) -> isize { if mem::size_of::<isize>() == 4 { rng.gen::<i32>() as isize } els...
Rust
0
time.sleep(self.panel_display_seconds) win = self._is_winning_turn() alternate_winning_display_image = None if win: winning_panel_image_file_path = _select_random_image_files_from_directory(_PANEL_IMAGE_DIRECTORY_PATH, 1)[0] winning_panel_image_background_c...
Python
1
= " \\param rev_leve revision level"] #[doc = " \\param dev_code device code"] #[doc = " \\param rel_date release date"] #[doc = " \\param pad[24] padding"] #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct _dvddrvinfo { pub rev_level: u16_, pub dev_code: u16_, pub rel_date: u32_, pub pad: [u8_; 24us...
Rust
0
for each kind. let num_terms = match kind { X2kind::S => 3, X2kind::T => 5, X2kind::V => 6, X2kind::M => match fun { 2 => 2, _ => 4, }, X2kind::L => 7, X2kind::E => 0, X2kind::J => 0, X2kind::FC => 0, }; // Make...
Rust
0
# pages/2_📊_Dashboard.py """ Dashboard Analítico - ChaskiWay - Estadísticas generales del sistema - Análisis de precios y tendencias - Visualizaciones interactivas - Métricas de rendimiento """ import streamlit as st import pandas as pd import plotly.express as px import plotly.graph_objects as go from plotly.subplot...
Python
1
from .logicaDifusa import LogicaDifusa class MotorInferencia: """ Clase encargada de realizar las consultas mediante razonamientos hacia atrás. """ @staticmethod def realizarConsulta(consulta, baseConocimiento, opDifusos): """ Dadas una consulta, una base de conocimiento, y los ti...
Python
1
= f"Prediction for {image_path}: Uncertain ({output * 100:.2f}%)" print(result) log_results(result) # Example predictions test_image_path = r"C:\\Users\\razda\\OneDrive\\Desktop\\First Degree\\Introduction to artificial intelligence\\AI Project\\Pictures\\Model_Data\\test_pic.png" predict_image(test_image_pa...
Python
1
from itertools import chain from django.views.generic import ListView from core.models import NewsAndEvents from course.models import Program, Course from quiz.models import Quiz class SearchView(ListView): template_name = "search/search_view.html" paginate_by = 20 count = 0 def get_context_data(self...
Python
1
(result_type.clone(), sql, stmt_info) { // // Have result type and SQL did not validate, try generating SELECT ... FROM (Some(ResultType { contents: Some(contents), .. }), sql, None) => { let result_type = contents.to_string(); let table_name = result_type.to_lowercase(); let tables = TABLES.lock().unwr...
Rust
0
#!/usr/bin/env python # encoding: utf-8 """ @author: sherlock @contact: sherlockliao01@gmail.com """ import sys sys.path.append('.') from fast_reid.fastreid.config import get_cfg from fast_reid.fastreid.engine import default_argument_parser, default_setup, launch from fast_reid.fastreid.utils.checkpoint import Chec...
Python
1
from .射线法 import 点在面内, 多点在面内 from .面积法 import 相交面积 from .判断透明 import 判断透明 from ...通用.信息 import 报告信息 import time import datetime import numpy as np from collections import defaultdict from concurrent.futures import ThreadPoolExecutor # def 检测单个面(点, 面数据): # 面顶点 = 面数据['UV坐标'] # # 包围盒过滤 # min_u = min(u for (u,...
Python
1
from detectron2.modeling.meta_arch.fcos import FCOS, FCOSHead from .retinanet import model model._target_ = FCOS del model.anchor_generator del model.box2box_transform del model.anchor_matcher del model.input_format # Use P5 instead of C5 to compute P6/P7 # (Sec 2.2 of https://arxiv.org/abs/2006.09214) model.backbo...
Python
1
ssert_eq!(cellv.len() , len, "Init failed due to incomplete OUTCAR"); let ion_iters = multizip((nscfv, totenv, toten_zv, magmomv, cputimev, ext_pressure, posv, forcev, cellv)) .map(|(iscf, e, ez, mag, cpu, stress, pos, f, cell)| { IonicIteration::new(iscf, e, ez, cpu, stress, mag...
Rust
0
# https://usaco.org/index.php?page=viewproblem2&cpid=987 input_file = open('word.in', 'r') output_file = open('word.out', 'w') lst = input_file.readline().split() n = int(lst[0]) k = int(lst[1]) words = input_file.readline().split() line = '' char_on_line = 0 for word in words: if char_on_line + len(word) <= k:...
Python
1
] self.bridge.addr_ranges = ranges[0] class DRAMSysDDR4_1866(DRAMSysMem): """ An example DDR4 1866 DRAMSys configuration. """ def __init__(self, recordable: bool): """ :param recordable: Whether the database recording feature of DRAMSys is enabled. """ super()....
Python
1
priv() { assert_eq!(Instruction::LDTRB_32_ldst_unpriv { imm9: 511, Rn: 31, Rt: 31, }.encode().decode(), Instruction::LDTRB_32_ldst_unpriv { imm9: 511, Rn: 31, Rt: 31, }) } #[test] fn roundtrip_LDRB_32_ldst_immpre() { assert_eq!(Instruction::LDRB_32_ldst_immpre { imm9: 511, Rn: 31, Rt: 31, }.enc...
Rust
0
for name in depth_names: if name not in depth_resize_size: logging.warning( f"No depth_resize_size was provided for depth_{name}. This will result in 1x1 " "padding depth images, which may cause errors if you mix padding and non-padding images." ) ...
Python
1
rror in {fc_path}") # Fix distributed_controller_anyio.py list_nodes method dc_path = "/home/barberb/ipfs_kit_py/ipfs_kit_py/mcp/controllers/distributed_controller_anyio.py" if os.path.exists(dc_path): with open(dc_path, 'r', encoding='utf-8') as f: content = f.read() # Replace...
Python
1
} #[cfg(test)] mod tests { use super::*; #[test] fn test_coordinate_from_str() { let coordinate = Coordinate::try_from("a1a"); assert!(coordinate.is_err()); let coordinate = Coordinate::try_from("a0"); assert!(coordinate.is_err()); let coordinate = Coordinate::tr...
Rust
0
input_im_info: data[2]}) summary_writer.add_summary(summary_str, global_step=step) if step != 0 and step % FLAGS.decay_steps == 0: sess.run(tf.assign(learning_rate, learning_rate.eval() * FLAGS.decay_rate)) if step % 10 == 0: avg_time_per_ste...
Python
1
DHCP_IPV6_ADDRESS, } impl ::core::marker::Copy for DHCPV6_IP_ARRAY {} impl ::core::clone::Clone for DHCPV6_IP_ARRAY { fn clone(&self) -> Self { *self } } #[doc = "*Required features: 'Win32_NetworkManagement_Dhcp'*"] pub const DHCPV6_OPTION_CLIENTID: u32 = 1u32; #[doc = "*Required features: 'Win32_Netw...
Rust
0
from flask import Blueprint, request, jsonify from models import Supermarkets from database import db supermarket_bp = Blueprint('supermarket', __name__) @supermarket_bp.route('/supermarkets/register', methods=['POST']) def register(): data = request.get_json() username = data.get('username') password = d...
Python
1
self.v.invert_channel()) } } impl<T:FloatChannel> FloatColor<T> for HSV<T> { /// Normalizes the components of the color. Modulo `360` is applied to the /// `h` component, and `s` and `v` are clamped to the range `(0,1)`. #[inline] fn normalize(&self) -> HSV<T> { HSV::new(se...
Rust
0
original order here. let bitflags = bitflags_map .into_iter() .map(|(k, mut values)| { values.sort_by_key(|(_, index, _)| *index); let values = values .into_iter() .map(|(name, _index, value)| (name, value)) .collect(); ...
Rust
0
"""sphinx configuration.""" from immutabledict import __version__ # Project info project = "immutabledict" copyright = "2023, corenting" author = "corenting" version = __version__ release = __version__ # General configuration extensions = [ "alabaster", "sphinx.ext.intersphinx", "sphinx.ext.autodoc", ...
Python
1
s, have=h_entries) def _compare_entries(self, want, have): for wk, wentry in iteritems(want): hentry = have.pop(wk, {}) self.compare(parsers=self.parsers, want=wentry, have=hentry) def _route_maps_list_to_dict(self, entry): entry = {x["route_map"]: x for x in entry} ...
Python
1
from fastapi import FastAPI from pydantic import BaseModel app =FastAPI() # Inicialización de los módulos conectados. modulosConectado = {"modulosDeteccion":[], "modulosActuacion":[]} @app.get("/get_modulos") async def getModulos(): """Función encargada de devolver los módulos conectados. Returns: j...
Python
1
bob = baker::ActiveModel { name: Set("<NAME>".to_owned()), contact_details: Set(serde_json::json!({ "mobile": "+61424000000", "home": "0395555555", "address": "12 Test St, Testville, Vic, Australia" })), bakery_id: Set(Some(bakery_insert_res.last_inser...
Rust
0