text string | label_name string | labels int64 |
|---|---|---|
y=1.05,
xref="paper",
yref="paper",
xanchor="right",
showarrow=False,
text="<b>" + legend_title + "</b>",
)
)
if len(scope) == 1 and scope[0].lower() == "usa":
xaxis_range_low = -125.0
xaxis_range_high = -55.0
yax... | Python | 1 |
!
# ie check API compatibility between hough_ellipse and ellipse_perimeter
rr2, cc2 = ellipse_perimeter(
y0, x0, int(best[3]), int(best[4]), orientation=best[5]
)
assert_equal(rr, rr2)
assert_equal(cc, cc2)
def test_hough_ellipse_non_zero_negangle4():
# ry < rx, angle in [-pi:-3pi/4]
... | Python | 1 |
= CocoDetection(img_folder, ann_file)
imageplane_coco = COCO(ann_file)
return imageplane_coco, img_folder
def get_bbox_in_pixels(polygon, buffer=2):
# Return the bounding box based on the max and min x and y coordinates
print("IMPLEMENT THIS")
min_x = np.min([p[0] for p in polygon])
max_x ... | Python | 1 |
params=query_params_dict,
json=body_data or None,
timeout=error_handling.get("timeout", 30),
)
if response.status_code >= 400:
raise requests.exceptions.HTTPError(
f"Error in the request: {respons... | Python | 1 |
Limit::Explicit,
)?;
self
.ser
.respond(RequestKind::Question, "Add entry?", "no")?;
self.ser.end_scope()?;
self.ser.end_scope()
}
}
impl<'a, P: PromptResponder> ser::SerializeStruct for &'a mut Serializer<P> {
type Ok = ();
type Error = Error;
fn serialize_field<T>(&mut self, key:... | Rust | 0 |
ics: u16::from(specific_fields_64.dll_characteristics),
size_of_stack_reserve: u64::from(specific_fields_64.size_of_stack_reserve),
size_of_stack_commit: u64::from(specific_fields_64.size_of_stack_commit),
size_of_heap_reserve: u64::from(specific_fields_64.size_of_heap_reserve),
... | Rust | 0 |
from typing import Any, Dict, Optional, Union
import pytest
from torch.nn import Module
from transformers import AutoModelForCausalLM, Trainer
from llmcompressor.core import active_session
from llmcompressor.transformers.finetune.session_mixin import SessionManagerMixIn
class MixInTest(SessionManagerMixIn, Trainer)... | Python | 1 |
scodeCurrentMirror",
"MosfetNormalArray",
"MosfetCascodeCurrentMirror",
"MosfetCascodedAnalogInverter",
"MosfetCascodeAnalogInverterNmosDiodeTransistor",
"MosfetWilsonCurrentMirror",
"MosfetCascodeNMOSAnalogInverterOneDiodeTransistor",
... | Python | 1 |
:
smoothed_spectrum[:, fc_index] = 0
continue
sumproduct = np.zeros(nspectra)
sumwindow = 0
for f_index, f in enumerate(frequencies):
f_on_fc = f / fc
if (f < 1E-6) or (f_on_fc < lower_limit) or (f_on_fc > upper_limit):
continue
... | Python | 1 |
ition_preorder(ident: &str, ast: &MojomAst) -> Option<Location> {
let mut path = Vec::new();
for traversal in preorder(&ast.mojom) {
let loc = match traversal {
Traversal::EnterInterface(node) => {
let loc = match_field(ident, &node.name, ast, &mut path);
let ... | Rust | 0 |
from typing import List
from urllib.parse import urlparse
from botocore.exceptions import ClientError
from django.apps import apps
from django.conf import settings
from rest_framework import serializers
from upload.models import Image
client = settings.S3_CLIENT
BUCKET_NAME = settings.MEDIA_BUCKET_NAME
class InIma... | Python | 1 |
firewall policy associations. A
network firewall policy is a set of rules that controls access to various
resources.
"""
_support_priority = False
_support_associated_policy_to_be_replaced = False
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(Create):
"""Create a... | Python | 1 |
"available": "2",
"used": "2",
"config": "UU",
},
},
"uptime": "3 days, 10:25:20",
}
HA_SENSOR_DATA: dict[str, Any] = {
"fs": {
"/ssl": {"disk_use": 30.7, "disk_use_percent": 6.7, "disk_free": 426.5},
"/media": {"disk_use": 30.7, "disk_use_percent": 6.7, "di... | Python | 1 |
T *
FROM exercise_tasks et
WHERE et.id = $1;
",
exercise_task_id
)
.fetch_one(conn)
.await?;
Ok(exercise_task.model_solution_spec)
}
<filename>src/uniprot/model/comment/alternative_product.rs
use std::io::BufRead;
use std::str::FromStr;
use quick_xml::events::BytesStart;
use quick_xml::Read... | Rust | 0 |
ailures due to Port Conflicts
//!
//! If the test has a port conflict with another test, or another process, then it will fail.
//! If these conflicts cause test failures, run the tests in an isolated environment.
//!
//! ## Failures due to Configured Network Interfaces
//!
//! If your test environment does not have an... | Rust | 0 |
match #binding1.der_cmp(&#binding2)? {
::core::cmp::Ordering::Equal => (),
other => return Ok(other),
}
}
}
}
<reponame>Lapz/tokio-postgres-mapper
#[macro_use]
extern crate tokio_postgres_mapper_derive;
#[derive(PostgresMapper)]
pub struct User {
... | Rust | 0 |
'''
2025电赛E题找A4 UV纸圆心,可以找到圆心和第三个圆圈,帧率 > 25fps。
有多种设置和算法,根据实际情况选择。
控制云台可以基于中心点误差 err_center 进行 PID 控制
@author Neucrack@sipeed & lxo@sieed 协助
@license MIT
@date 2025.7.30
'''
from enum import auto
from maix import camera, display, image, nn, app, time
import cv2
import numpy as np
DEBUG=False
PR... | Python | 1 |
rrow<Q>,
Q: Hash + Eq,
{
let mut hasher = self.hasher();
k.hash(&mut hasher);
let displace_index = hasher.finish() % self.len as u64;
let displace = unsafe { self.displace(displace_index as usize) };
let index = if displace == u32::MAX {
return None;
... | Rust | 0 |
::new("b".into(), base_constrs()),
Req::new("c".into(), base_constrs()),
],
&[Req::new("dev_b".into(), base_constrs())],
);
let expected = r#"
[tool.pyflow]
name = ""
[tool.pyflow.dependencies]
b = "^0.0.1"
c = "^0.0.1"
[tool.pyflow.dev-dependencies]
dev_a = "^... | Rust | 0 |
_selected_reply`]: XcbShape::xcb_shape_input_selected_reply
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct xcb_shape_input_selected_cookie_t {
/// The sequence number of the request.
pub sequence: c_uint,
}
impl Default for xcb_shape_input_selected_cookie_t {
fn default() -> Self {
unsafe { st... | Rust | 0 |
end("Você precisa enviar uma imagem com o comando `!pb`.")
@commands.command(name='ajuda')
async def ajuda(self, ctx):
"""Mostra todos os comandos disponíveis."""
embed = discord.Embed(
title="Comandos do Bot",
description="Use `!` seguido de um comando e anexe sua image... | Python | 1 |
ng. Will collect and concatenate all
AccessInducer result strings and return it. Returns None if no string fetched from AccessInducer
objects. As every AccessInducer invocation is putted in try block, any Exception caught will be
logged and skipped.
"""
current_view = str()
for inducer in self.keysof("... | Python | 1 |
"""
Download all EXPASY amino acid scales.
Collaborative work done by Kannan Sankar, Mei Xiao and Eric Ma.
Extracts all amino acid properties from EXPASY,
and dumps them as a CSV file.
If you use the scales that are downloaded by this script,
please make sure that you cite ProtScale.
Reference is here: https://web.e... | Python | 1 |
llect::<Vec<_>>(), vec![9]);
assert_eq!(find_hit(0, &(-10..=-5)).collect::<Vec<_>>(), vec![5, 4]);
}
#[test]
fn sample_part1() {
test_implementation(part1, SAMPLE, 45);
}
#[test]
fn sample_part2() {
test_implementation(part2, SAMPLE, 112);
}
}
extern crate gen_epub_... | Rust | 0 |
bers and returns the value at mat[row][column].
This sum formula should exist until this cell is overlapped by another value or another sum formula. numbers[i] could be on the format:
"ColRow" that represents a single cell.
For example, "F7" represents the cell mat[7]['F'].
... | Python | 1 |
in", ASIN, 225 );
( "atan", ATAN, 226 );
( "atan2", ATAN2, 227 );
( "ceil", CEIL, 228 );
( "cos", COS, 229 );
( "exp", EXP, 230 );
( "random", RANDOM, 231 );
( "sin", SIN, 232 );
( "sqrt", SQRT, 233 );
( "tan", TAN, 234 );
( "round", ROUND, 235 );
( "toExponential"... | Rust | 0 |
raw: FatPtr { data, len },
}
.rust_mut
}
}
/// A local `const fn` version of `slice::from_raw_parts`.
#[inline(always)]
pub(crate) const fn slice_from_raw_parts<'a, T>(data: *const T, length: usize) -> &'a [T] {
// Same code as in the original, except we do the debug assertions in the function that this on... | Rust | 0 |
oa.pa10.into_alternate_af1(cs);
// Set up serial port
let mut serial = Serial::usart1(p.USART1, (tx, rx), 115200.bps(), &mut rcc);
serial.write_str("Type for echo!\n\r").ok();
loop {
let received = block!(serial.read()).unwrap();
block!(... | Rust | 0 |
assert_eq!(r.is_ok(), true);
//
let (r, sioe) = do_execute!(&["-s", "\"cats\".[2:1]"], super::IN_DAT_04);
assert_eq!(buff!(sioe, serr), "");
assert_eq!(
buff!(sioe, sout),
"[{\"third\":\"Misty\"},{\"second\":\"Kitkat\"}]\n",
);
assert_eq!(... | Rust | 0 |
possession require distinct messages because the
/// message must uniquely single out the signing key, so they may be
/// aggregated or batch verified with distinct message mode, and
/// indeed using distinct messages aggregation is optimal.
///
/// We recommend using this for either batching or aggregation, but
/// we... | Rust | 0 |
st_gated_blocks_rendered_with_basic_info(self):
"""
Test that gated blocks are rendered with minimal metadata when prerequisites are not met.
"""
# Mock child block
child = Mock()
child.scope_ids.usage_id = "block1"
child.scope_ids.block_type = "vertical"
... | Python | 1 |
from .indexdata import get_index_data
from .base import load_context, load_local_search_engine, load_basic_search_engine, load_drift_search_engine, load_global_search_engine
| Python | 1 |
# pip install li-group-center
# OpenCV push to RTSP Server example
# Author: Haomin Kong
import time
import cv2
import numpy as np # 添加numpy导入 / Add numpy import
from group_center.tools.rtsp.rtsp_push import RtspPush
video_path: str = "test.mp4" # 视频文件路径 / Video file path
server_url: str = r"" # RTSP服务器地址 / RTSP... | Python | 1 |
# Generated by Django 5.1.1 on 2024-09-27 06:20
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('boipoka_app', '0002_book_image'),
migrations.swappable... | Python | 1 |
import os
import yaml
import sys
from typing import Dict, Optional
CONFIG_PATH = "config.yaml"
KEY_PATH = "key.yaml"
def get_resource_path(relative_path):
"""获取资源文件的绝对路径,兼容开发环境和打包环境"""
if getattr(sys, 'frozen', False):
# 打包后的环境
base_path = sys._MEIPASS
else:
# 开发环境
base_pa... | Python | 1 |
self.span.slice(source).tagged(self)
}
pub fn tagged_string<'a>(&self, source: &'a str) -> Tagged<String> {
self.span.slice(source).to_string().tagged(self)
}
pub fn anchor_name(&self) -> Option<String> {
match self.anchor {
Some(AnchorLocation::File(ref file)) => S... | Rust | 0 |
packet: Packet,
version_sum: usize,
}
impl From<&str> for Transmission {
fn from(input: &str) -> Self {
let bits = hex_to_bits(input);
let (packet, _, version_sum) = parse_packet(&bits);
Transmission {
packet,
version_sum,
}
}
}
#[derive(Debug, P... | Rust | 0 |
#!/usr/bin/env python
# Copyright (c) 2021, 2023 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
from ads.secrets import SecretKeeper
from base64 import b64encode
import pytest
from unittest.mock import patch
@pytest.fixture
def ... | Python | 1 |
"""
NOTE: this tests are also meant to be run as PyPy "applevel" tests.
This means that global imports will NOT be visible inside the test
functions. In particular, you have to "import pytest" inside the test in order
to be able to use e.g. pytest.raises (which on PyPy will be implemented by a
"fake pytest module")
""... | Python | 1 |
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File: LinuxBashShellScriptForOps:get_rds_backup.py
User: Guodong
Create Date: 2017/7/21
Create Time: 15:17
Description:
References: RDS MySQL备份文件下载工具
https://h... | Python | 1 |
,
#[doc = "20: Reference resistor tap for setting 20."]
CEREF1_20 = 20,
#[doc = "21: Reference resistor tap for setting 21."]
CEREF1_21 = 21,
#[doc = "22: Reference resistor tap for setting 22."]
CEREF1_22 = 22,
#[doc = "23: Reference resistor tap for setting 23."]
CEREF1_23 = 23,
#[... | Rust | 0 |
reponame>GuillaumeGomez/gtk3-rs
// Take a look at the license at the top of the repository in the LICENSE file.
/// No-op.
macro_rules! assert_initialized_main_thread {
() => {};
}
/// No-op.
macro_rules! skip_assert_initialized {
() => {};
}
<reponame>RainbowCookie32/rusty-psn
use std::io::Write;
use std::pa... | Rust | 0 |
from django.db import migrations
def update_at_building_id(apps, schema_editor):
Organization = apps.get_model("orgs", "Organization")
for org in Organization.objects.all():
profiles = org.columnmappingprofile_set.filter(mappings__contains=[{"to_field": "Audit Template Building Id"}])
for prof... | Python | 1 |
&[VideoFlag::DoubleBuf]) {
Ok(screen) => screen,
Err(err) => panic!("failed to set video mode: {}", err)
};
// Note: You'll want to put this and the flip call inside the main loop
// but we don't as to not startle epileptics
for i in 0usize..10 {
... | Rust | 0 |
import pandas as pd
from woodwork.column_schema import ColumnSchema
from woodwork.logical_types import Datetime
from featuretools.primitives.base.transform_primitive_base import TransformPrimitive
from featuretools.primitives.standard.transform.time_series.utils import (
_apply_gap_for_expanding_primitives,
)
cl... | Python | 1 |
qià,kān"),
('䁎', "chéng,tíng,chēng"),
('䁏', "yǎo"),
('䁐', "yīng,yìng"),
('䁑', "yáng"),
('䁒', "jí,zí"),
('䁓', "zōng,zǒng,jiè"),
('䁔', "xuān,hàn"),
('䁕', "mín"),
('䁖', "lōu"),
('䁗', "kǎi"),
('䁘', "yǎo"),
('䁙', "yǎn"),
('䁚', "sǔn,qióng"),
('䁛', "guì"),
('䁜', "huà... | Rust | 0 |
"DEBUG: Could not extract weekly program, returning empty dict")
weekly_program = {}
return weekly_program
def format_program(self, program: dict[str, str | None]) -> dict:
"""Ensure the program is in the correct format for the web application."""
draft = program['draft... | Python | 1 |
keydown(KeyboardEvent)
onkeypress(KeyboardEvent)
onkeyup(KeyboardEvent)
onloadstart(ProgressEvent)
onprogress(ProgressEvent)
onloadend(ProgressEvent)
onmousedown(MouseEvent)
onmouseenter(MouseEvent)
onmouseleave(MouseEvent)
onmousemove(MouseEvent)
onmouseout(MouseEvent)
onm... | Rust | 0 |
m = float(input("Digite o valor de volume metros cúbicos: "))
l = 1000 * m
print(l) | Python | 1 |
, 12, 31);
test_extract(1969, 12, 30);
test_extract(1970, 1, 1);
test_extract(1999, 10, 21);
test_extract(9999, 12, 31);
}
#[test]
fn test_now() {
let now = Local::now().naive_local();
let dt = Date::now().unwrap();
assert_eq!(now.year() as i32, dt.ye... | Rust | 0 |
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
#DATABASE_URL = "mysql+mysqlconnector://root:Kyronhardwick1@localhost:3306/students" # Replace with your credentials
DB_DIALECT = "mysql"
import os
from dotenv... | Python | 1 |
eshold_for_linear =
F::from(self.config.variation_threshold_for_linear).unwrap();
match self.config.order {
1 => interp_scalar_field_in_known_grid_cell_1d::<_, _, 2>(
field,
interp_coord,
interp_idx,
variation_threshold_for_... | Rust | 0 |
#!/usr/bin/env python3
"""
launch sensor related nodes
"""
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration, PathJoinSubstitution
from launch_ros.actions import Node
from launch_ros.substitutions import FindPackageShare
def gen... | Python | 1 |
passwd" => op_passwd(db_path),
"add" => op_add(db_path),
"list" => {
match keychain::V3::open(&db_path, &ask_password("Password: ")) {
Some(kc) => op_list(&kc, &op[1..]),
None => {},
}
},
"copy" => {
match keychain::V3::... | Rust | 0 |
# 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 |
async_trait]
impl EventHandler for Handler {
async fn ready(&self, _: Context, ready: Ready) {
info!("Connected as {}", ready.user.name);
}
async fn resume(&self, _: Context, _: ResumedEvent) {
info!("Resumed");
}
}
#[group]
#[commands(name, about)]
struct General;
#[tokio::main]
asyn... | Rust | 0 |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from vision_toolkit.scanpath.similarity.distance_based.distance_based_base import DistanceBased
from vision_toolkit.visualization.scanpath.similarity.distance_based.point_mapping import plot_mannan_eye_analysis
class EyeAnalysisDistance(Dist... | Python | 1 |
from datetime import datetime
from yweb.orm import ORMBase
from app.auth.models import User
from sqlalchemy import Column, Integer, BigInteger, String, \
Sequence, DateTime, Table, ForeignKey, Boolean, Text
from sqlalchemy.orm import backref,relationship
class Message(ORMBase):
__tablename__ = 'message'
... | Python | 1 |
# Author: Zhang Huangbin <zhb@iredmail.org>
import web
import settings
from libs import form_utils
from libs.iredapd import throttle as iredapd_throttle
if settings.backend == 'ldap':
from libs.ldaplib import decorators
else:
from libs.sqllib import decorators
# server-wide throttle setting.
class GlobalT... | Python | 1 |
opt = geoopt.optim.RiemannianSGD([M], lr=1e-3, momentum=0.9, weight_decay=1e-4)
sched = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(opt, 5000, 2, 1e-4)
def loss():
b = M[:,0]
if args.gpca_dim == 1:
Xp = proj_geodesic(data_all, b, M[:,1])
... | Python | 1 |
Check if config file exists
if not os.path.exists(CONFIG_FILE):
print(f'{CONFIG_FILE} not found. Creating a new one...')
config = setup_config()
else:
config = read_config()
if not validate_config(config):
print(... | Python | 1 |
PartialEq, Hash)]
pub enum WeierstrassCurveKind {
/// The NIST P-256 (a.k.a. prime256v1, secp256r1) elliptic curve defined in
/// FIPS 186-4: Digital Signature Standard (DSS).
///
/// <https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf>
NistP256,
/// The NIST P-384 (a.k.a. secp384r1) e... | Rust | 0 |
#!/usr/bin/env python
# Copyright 2012 Brno University of Technology (author: Karel Vesely)
# 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
#
... | Python | 1 |
SignedHeader> = shh.into();
assert_eq!(hashed, round);
}
}
#![allow(dead_code)]
use dataview::Pod;
#[derive(Pod)]
#[repr(C)]
/// doc comment
struct Struct1 {
field1: i32,
}
#[derive(Pod)]
/// doc comment
#[repr(C)]
struct Struct2 {
field1: i32
}
#[derive(Pod)]
#[allow(dead_code)]
/// doc comment
#[do... | Rust | 0 |
EN_RECT.width - morale_text.get_width() - 10, 10))
if self.level_up_timer > 0:
level_up_text = self.level_up_font.render("Level Up!", True, (255, 255, 0))
text_rect = level_up_text.get_rect(center=(SCREEN_RECT.centerx, SCREEN_RECT.centery - 100))
self.screen.blit(level_up_tex... | Python | 1 |
from reportlab.lib.units import cm
from reportlab.platypus.doctemplate import PageTemplate, SimpleDocTemplate
from reportlab.platypus.frames import Frame
from reportlab.platypus.paragraph import Paragraph
# noinspection PyPep8Naming,PyUnresolvedReferences
class MyDocTemplate(SimpleDocTemplate):
def __init__(self... | Python | 1 |
sponse.add_matched(key);
} else {
response.add_missing(key);
}
});
response
}
<filename>src/credentials.rs
use error::S3Result;
use std::env;
use dirs;
use ini::Ini;
/// AWS access credentials: access key, secret key, and optional token.
///
/// # Example
///
/// Loads from the stan... | Rust | 0 |
IllegalEscapeSequence(msg) => {
write!(f, "illegal escape sequence in string or bytes: {}", msg)
}
ParseFloat(err) => write!(f, "float parsing error: {}", err),
NumericCast(value, to_type) => {
write!(f, "error casting number: {} to {}", value, to_... | Rust | 0 |
66, "crust", "Crust Network, standard account (*25519).")
EquilibriumAccount =>
(67, "equilibrium", "Equilibrium Network, standard account (*25519).")
SoraAccount =>
(69, "sora", "SORA Network, standard account (*25519).")
MantaAccount =>
(77, "manta", "Manta Network, standard account (*25519).")
CalamariAcco... | Rust | 0 |
ret
}
fn to_f16(&self, rnd: RoundingMode) -> F16 {
rnd.set();
let ret = unsafe { softfloat_sys_riscv::f128_to_f16(self.0) };
F16::from_bits(ret.v)
}
fn to_f32(&self, rnd: RoundingMode) -> F32 {
rnd.set();
let ret = unsafe { softfloat_sys_riscv::f128_to_... | Rust | 0 |
it;
if !lnd_itest.exists() {
cmd_unit!(
%"tar -xzvf",
lnd_tarball().await,
"-C", target_dir()
);
let src_dir = target_dir().join("lnd-source");
cmd_unit!(
%"make build build-itest",
CurrentDir(&src_dir)
);
fs::copy(src_dir.join("lncli-debug"), &lncli_debug).unwrap... | Rust | 0 |
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain ... | Python | 1 |
].
///
/// This function returns a mutable slice of [`std::mem::MaybeUninit<T>`]. This is done
/// because it is undefined behavior in Rust to construct a `&` (or `&mut`) reference
/// to a value which has not been initialized. Note that it is undefined behavior even
/// if the reference is never re... | Rust | 0 |
#!/usr/bin/env python3
from typing import List, Optional
from collections import Counter, deque, defaultdict
from heapq import heapify, heappush, heappop
class Solution:
def maxAdjacentDistance(self, nums: List[int]) -> int:
res = float('-inf')
for i in range(1, len(nums)):
res = max(r... | Python | 1 |
onic;
}
use crate::argv::env;
use crate::error::ConfigError;
use crate::raw::{Config, Rules};
use crate::{argv, get_hostname};
use http::types::params::{Params, Tags};
use java_properties::PropertiesIter;
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;
use std::str::Fr... | Rust | 0 |
;
},
ResponseType::Repeat => {
let message_to_send = message_text
.split(":")
.into_iter()
.skip(1)
... | Rust | 0 |
Conceptual/CocoaTextArchitecture/TextEditing/TextEditing.html#//apple_ref/doc/uid/TP40009459-CH3-SW3
#![allow(clippy::upper_case_acronyms, non_snake_case)]
use std::ffi::c_void;
use std::ops::Range;
use std::os::raw::c_uchar;
use super::window::with_edit_lock_from_window;
use crate::kurbo::Point;
use crate::text::{
... | Rust | 0 |
def max_sunny_streak(days):
n = len(days)
max_streak = 0
foundP = False
for i in range(n):
if days[i] == 'P':
foundP = True
# Count S's to the left
left = 0
j = i - 1
while j >= 0 and days[j] == 'S':
left += 1
... | Python | 1 |
0, -0.002)],
["CE2", 5, (2.104, -1.201, -0.003)],
["OH", 5, (4.168, -0.002, -0.005)],
["CZ", 5, (2.791, -0.001, -0.003)],
],
"VAL": [
["N", 0, (-0.494, 1.373, -0.000)],
["CA", 0, (0.000, 0.000, 0.000)],
["C", 0, (1.527, -0.000, -0.000)],
["CB", 0, (-0.533,... | Python | 1 |
cls, :]
roidb[im_i]['bbox_targets'][cls_indexes, 1:] /= stds[cls, :]
return means.ravel(), stds.ravel()
def expand_bbox_regression_targets(bbox_targets_data, num_classes):
"""
expand from 5 to 4 * num_classes; only the right class has non-zero bbox regression targets
:param bbox_targets_d... | Python | 1 |
# -*- coding: utf-8 -*-
#
# RERO ILS
# Copyright (C) 2019-2022 RERO
# Copyright (C) 2019-2022 UCLouvain
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# Thi... | Python | 1 |
import pygame
import esper
from src.ecs.components.c_surface import CSurface
from src.engine.service_locator import ServiceLocator
def system_update_shield_counter(
ecs_world: esper.World,
entity: int,
shield_info: dict,
time_counter: float,
last_shield_created_at: float,
... | Python | 1 |
slf.pad_function_bodies(module);
}
fn pad_cosntant_table(&mut self, module: &mut CompiledModuleMut) {
// TODO actual constant generation
module.constant_pool = vec![]
}
fn pad_identifier_table(&mut self, module: &mut CompiledModuleMut) {
module.identifiers = (0..(self.... | Rust | 0 |
diagnostics: diagnostics.clone(),
uri: url.clone(),
version: None,
};
publish_diagnostic(params, &self.sender).ok();
}
}
}
impl ErrorReporter for LSPErrorReporter {
fn report_diagnostic(&self, diagnostic: &CompilerDiagnostic) {
let message... | Rust | 0 |
# coding: utf-8
"""
Python SDK for Logto API
Python SDK for Logto API. Note: This SDK is for Logto Cloud and OSS. However, if you are using Logto OSS, some features available in the SDK may not work for you. Please refer to the response of `/api/swagger.json` endpoint on your Logto OSS instance for features ... | Python | 1 |
a register by index
/// Range: 0-31
pub type Register = u8;
/// index into the sreg-register
/// Range: 0-7
pub type SREG = u8;
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum LDMode {
PostIncrement,
PreDecrement,
Displacement(u8)
}
impl LDMode {
#[inline(always)]
#[allow(dead_code)]
pu... | Rust | 0 |
:TimedOut,
// `TimedOut` and `Free` both don't perform any speculation and therefore should be the same
// for our purposes here. In other words, if `TimedOut` matched then the `Free` must be
// matched as well.
];
// Consider running these checks in parallel to reduce validation latency.
for assumption in AS... | Rust | 0 |
# Copyright (c) Alibaba, Inc. and its affiliates.
from dataclasses import dataclass
from typing import Optional
from swift.llm import safe_snapshot_download
from swift.utils import find_free_port, get_logger
from .infer_args import InferArguments
logger = get_logger()
@dataclass
class DeployArguments(InferArguments... | Python | 1 |
x[sim_ids, sample] = 1 - x[sim_ids, sample]
v = sim.get_scores(x)
xs[i] = x
vs[i] = v
logprobs[i] = dist.log_prob(sample)
vs_max = vs.max(dim=0)[0]
mask = th.eq(vs_max, vs_max.max())
obj_logprob = logp... | Python | 1 |
data = vec![0u8; 256];
data[2] = 127;
let element = IconElement::new(OSType(*b"s8mk"), data);
let image = element.decode_image().expect("failed to decode image");
assert_eq!(image.pixel_format(), PixelFormat::Alpha);
assert_eq!(image.width(), 16);
assert_eq!(image.height... | Rust | 0 |
_utf8 += 1;
},
Some('а' ..= 'я') | Some('ё') => {
q_russian_utf8 += 1;
q_russian_small_utf8 += 1;
},
Some('A' ..= 'Z') => {
q_engl_utf8 += 1;
q_engl_big_utf8 += 1;
},
Some('a' ..= 'z') => {
q_engl_utf8 += 1;
q_engl_small_utf8 += 1;
},
Some('#') => while_match!((iter, a, q_comm... | Rust | 0 |
first='eliud'
last='gathuthi'
sport='basketball'
girlfriend='makena'
mum= 'magdaline'
msg=f'''dear {mum} we are very excited to inform you of the news regarding you child
{first} [{last}] who due to his excellent {sport} skills has been nominated to the team kenya.
his girlfriend {girlfriend} will be escort... | Python | 1 |
ist
prev[w] = [word]
elif alt_dist == dist[w]: # key!
prev[w].append(word)
paths = [path+[end] for path in recover_paths(end, prev)]
print paths
return paths
def recover_paths(end, prev):
if len(prev[end]) == 0: yield []
else:
for word in pre... | Python | 1 |
ion. The other is more akin to a C++
//transform of a heterogeneous collection. For that we might want to pass a path or ident
//instead of the token tree. Because the token tree is just a trick to get lambdas
//as well. But since the other way isn't great for lambdas anyway we can j... | Rust | 0 |
import functools
import time
import json
# 导入统一日志系统
from core.utils.logging_init import get_logger
logger = get_logger("default")
# 导入提示词加载器
from core.agents.prompt_loader import get_prompt_loader
# 导入i18n功能
from core.i18n.messages import get_language_name_for_prompt
def create_trader(llm, memory):
def trader_n... | Python | 1 |
}
};
}
//! Provides stuff related to log levels
use std::{fmt, str::FromStr};
use cfg_if::cfg_if;
use crate::Error;
pub(crate) const LOG_LEVEL_NAMES: [&str; Level::count()] =
["critical", "error", "warn", "info", "debug", "trace"];
/// An enum representing log levels.
///
/// Typical usage include... | Rust | 0 |
self.b /= rhs;
}
}
/* TYPE CONVERSION */
impl From<[f64; 3]> for Color {
fn from(arr: [f64; 3]) -> Self {
Color {
r: arr[0],
g: arr[1],
b: arr[2],
}
}
}
impl From<Color> for [f64; 3] {
fn from(v: Color) -> Self {
[v.r, v.g, v.b]
}... | Rust | 0 |
import PyPDF2
pdfiles=["sample.pdf","dummy.pdf"]
merger = PyPDF2.PdfMerger()
for filename in pdfiles:
pdfFile = open(filename, 'rb')
pdfReader = PyPDF2.PdfReader(pdfFile)
merger.append(pdfReader)
pdfFile.close()
merger.write('merged.pdf') | Python | 1 |
as syn::ItemMod);
let attrs = ty.attrs;
let vis = ty.vis;
let rs = ty.ident;
let __gf = Ident::new(&format!("__{}_gf", rs.to_string()), Span::call_site());
let __u = Ident::new(&format!("__{}_u", rs.to_string()), Span::call_site());
// overrides in parent's namespace
let mut overrides = ... | Rust | 0 |
_id: TxnId, coord: Coord, value: Number) -> TCResult<()> {
let coord = self.rebase.invert_coord(&coord);
self.source.write_value(txn_id, coord, value).await
}
}
impl<T: SparseAccess> ReadValueAt for SparseExpand<T> {
fn read_value_at<'a>(&'a self, txn: &'a Txn, coord: Coord) -> Read<'a> {
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.