text string | label_name string | labels int64 |
|---|---|---|
import random
elements = {1:"SNAKE",2:"WATER",3:"GUN"}
score={"WINS":0,"LOSES":0,"DRAWS":0}
def Play():
#'''
# First an input is taken from user
# But if the input is not valid(ValueError or not in [1,2,3]),
# then the iteration goes in the except loop and appropriate message is displayed.
#''... | Python | 1 |
size, key_file=shape_files[0], drop_last=drop_last
)
elif type == "sorted":
retval = SortedBatchSampler(
batch_size=batch_size,
shape_file=shape_files[0],
sort_in_batch=sort_in_batch,
sort_batch=sort_batch,
drop_last=drop_last,
)
... | Python | 1 |
me HLO from `numerics.abs_sq`,
# `jnp.square(x)`, `x * x`, and `x**2`.
real_sq_fns = (lambda x: x**2, lambda x: x * x, jnp.square)
def _get_hlo_repr(f, x):
hlo_string = jax.jit(f).lower(x).compiler_ir(dialect="hlo").as_hlo_text()
return re.sub(
"HloModule.*?\n", "", re.sub("ENTRY.*?{... | Python | 1 |
hv) = from_hex_digit(h) {
if let Some(l) = bytes.next() {
if let Some(lv) = from_hex_digit(l) {
out.push(hv * 16 + lv);
break;
} else {
out.push... | Rust | 0 |
None)
};
let grouper_date = if let Some(date_format) = format {
Grouper::ByDate(Some(date_format))
} else {
Grouper::ByDate(None)
};
let value_result = match (grouper_date, grouper_column) {
(Grouper::ByDate(None), GroupByColumn::Name(None)) ... | Rust | 0 |
ShardKey {
pub fn add_int(mut self, n: impl Into<i64>) -> Self {
self.0.append(&n.into().to_be_bytes());
self
}
pub fn add_str(mut self, s: &str) -> Self {
self.0.append(s.as_bytes());
self
}
fn hash(self) -> u32 {
self.0.finalize64() as u32
}
}
#[cfg(... | Rust | 0 |
code: i32) -> Self {
self.code = code;
self
}
pub fn with_data(mut self, data: impl Serialize) -> Self {
self.data = Some(serde_json::to_value(data).unwrap());
self
}
pub fn parse() -> Error {
Error {
code: -32700,
message: "Parse error"... | Rust | 0 |
lass', 'education', 'marital_status', 'occupation', 'relationship', 'race', 'sex', 'native_country']
# 选择前4个分类变量进行可视化
selected_cat_features = cat_features[:4]
fig, axes = plt.subplots(2, 2, figsize=(18, 12))
axes = axes.flatten()
for i, feature in enumerate(selected_cat_features):
# 获取前10个最频繁的类别
value_counts ... | Python | 1 |
# -*- coding: utf-8 -*-
# Script Mapping for Devanagari
VowelMap = [
'\u1022',
'\u1022ႃ',
'\u1022\u102D',
'\u1022\u102E',
'\u1022\u102F',
'\u1022\u1030',
'ရိ\u02BD',
'ရီ\u02BD',
... | Python | 1 |
import os.path as osp
import unittest
import numpy as np
from mmdet.registry import TRANSFORMS
from mmdet.utils import register_all_modules
register_all_modules()
class TestInstaboost(unittest.TestCase):
def setUp(self):
"""Setup the model and optimizer which are used in every test method.
Te... | Python | 1 |
pprove::new(logger, interfaces);
let disapprove = self::action_disapprove::Disapprove::new(logger, interfaces);
let orchestrate = self::orchestrate::Orchestrate::new(logger, interfaces);
let synthetic_view = self::synthetic_view::SyntheticView::new(logger, interfaces);
move |conf| {
APIRoot::Uns... | Rust | 0 |
.enable_scons_dump()
.enable_c_entry_points()
.options(build::env_options_iter("ESP_IDF_SYS_PIO_CONF")?)
.files(build::tracked_globs_iter(path_buf!["."], &["patches/**"])?)
.files(build::tracked_env_globs_iter("ESP_IDF_SYS_GLOB")?);
let manifest_dir = PathB... | Rust | 0 |
A}\u{0036}",
"--ned --remove-default-ignorables",
),
"P|\
Q@333,0|\
R@699,0|\
A@1050,0|\
B@1880,0|\
X@2710,0|\
Y@3074,0|\
Z@3406,0|\
six@3728,0"
);
}
#[test]
fn morx_4_007() {
assert_eq!(
shape(
... | Rust | 0 |
html) module"]
pub struct SR0_SPEC;
impl crate::RegisterSpec for SR0_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [sr0::R](R) reader structure"]
impl crate::Readable for SR0_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [sr0::W](W) writer structure"]
impl crate::Writable for SR0_SP... | Rust | 0 |
_PAD_GPIO_AD_B0_13,
}
uart! {
module::_3,
tx: GPIO_AD_B1_06<Alt2>, SW_PAD_CTL_PAD_GPIO_AD_B1_06, LPUART3_TX_SELECT_INPUT, GPIO_AD_B1_06_ALT2,
rx: GPIO_AD_B1_07<Alt2>, SW_PAD_CTL_PAD_GPIO_AD_B1_07, LPUART3_RX_SELECT_INPUT, GPIO_AD_B1_07_ALT2,
}
uart! {
module::_4,
tx: GPIO_B1_00<Alt2>, SW_PAD_CTL_P... | Rust | 0 |
mosaicity = mosaicity_from_eigen_decomposition(eigen_values)
logger.info(
"""
Angular mosaicity in degrees equivalent units:\n"""
+ "\n".join(f" M{i + 1} : {m:.5f} degrees" for i, m in enumerate(mosaicity))
)
def print_matrix_np(A, fmt="%.3g", indent=0):
"""
Pretty print matrix
... | Python | 1 |
import os
import h5py
import matplotlib.pyplot as plt
import numpy as np
PATH = '/Volumes/large/Simon/mea1k/ttl_data/recordings/'
fname = "Trace_20240618_17_02_41_withBehaviorTTL.raw.h5"
fullfname = os.path.join(PATH, fname)
with h5py.File(fullfname, 'r') as file:
print(file.keys())
print(file['bits'])
p... | Python | 1 |
string += ('\n')
return string
@property
def penalty_variable_optimized(self):
return self.context.options.penalty_variable_optimized
@property
def penalty_irretrievable(self):
return self.context.options.penalty_irretrievable
@property
def penalty_not_evaluatable(... | Python | 1 |
`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB4TINVR {
#[doc = "Disable invert on trigger value."]
DIS,
#[doc = "Enable invert on trigger value."]
EN,
}
impl TMRB4TINVR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!s... | Rust | 0 |
be set to 1 to enable AES-CTR; selecting other AES modes than CTR mode is invalid."]
#[inline]
pub fn ccm(&mut self) -> _CCMW {
_CCMW { w: self }
}
#[doc = "Bit 15 - 15:15\\] MAC mode enable. The DIR bit must be set to 1 for this mode. Selecting this mode requires writing the AESDATALEN1.LEN_MS... | Rust | 0 |
.mul_add(s.0, 0.275_573_189_238_604_437_3_e-5)
.mul_add(s.0, 0.248_015_873_560_581_506_5_e-4)
.mul_add(s.0, 0.198_412_698_414_807_185_8_e-3)
.mul_add(s.0, 0.138_888_888_888_676_325_5_e-2)
.mul_add(s.0, 0.833_333_333_333_334_709_5_e-2)
.mul_add(s.0, 0.416_666_666_666_666_990_5_... | Rust | 0 |
# Generated by Django 3.2.10 on 2022-01-25 14:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("github", "0006_githubwebhookmessage_clone_status")]
operations = [
migrations.RenameField(
model_name="githubwebhookmessage",
old... | Python | 1 |
:TraceMeta;
use evm_rpc::*;
use evm_state::*;
use sha3::{Digest, Keccak256};
use jsonrpc_core::BoxFuture;
use jsonrpc_http_server::jsonrpc_core::*;
use jsonrpc_http_server::*;
use serde_json::json;
use snafu::ResultExt;
use solana_evm_loader_program::scope::*;
use solana_sdk::{
clock::MS_PER_TICK, fee_calculator... | Rust | 0 |
"""舰队问答类活动抄这个
后续做活动地图时截取简单活动页面,放在event_image,出击按钮为1.png,简单活动页面是2.png
"""
import os
from autowsgr.constants.data_roots import MAP_ROOT
from autowsgr.fight.event.event import Event
from autowsgr.fight.normal_fight import NormalFightInfo, NormalFightPlan
from autowsgr.timer import Timer
NODE_POSITION = (
None,
... | Python | 1 |
'
sun";
let expected: Vec<crate::Argument> = vec![
crate::Argument::PassThrough("--hello".into()),
crate::Argument::PassThrough("world".into()),
crate::Argument::PassThrough("@moon.txt".into()),
crate::Argument::PassThrough("--goodbye".into()),
crate::... | Rust | 0 |
imulator': 'spiNNaker',
'duration': 50, # Number of time steps to run each sample.
'num_to_test': 5, # How many test samples to run.
'batch_size': 1, # Batch size for simulation.
# SpiNNaker seems to require 0.1 for comparable results.
'dt': 0.1
}
config... | Python | 1 |
, default="cubic", choices=["cubic", "nearest","linear"],
help="Whether to resize the image's (height, width) dimensions to the specified `size`. Default(cubic)",
)
parser.add_argument(
"--do_center_crop", type=bool, default=True,
help="Whether to center crop the image to the specified `... | Python | 1 |
ce=True)
beh_long.fillna("n/a", inplace=True)
# Remove unnamed columns
beh_long = beh_long.loc[:, ~beh_long.columns.str.contains("^Unnamed")]
# Save to bids path
beh_long.to_csv(
opj(
param.bidspath,
p,
... | Python | 1 |
from nexmark import Query
from psycopg2._psycopg import connection
class Query6(Query):
def create_sources(self):
self.execute_sql(self.bid_source_sql)
self.execute_sql(self.auction_source_sql)
def create_materialized_view(self):
query = """
CREATE MATERIALIZED... | Python | 1 |
l_rejected: false,
is_reconnect: false,
}
}
}
<filename>src/link_intersection.rs
use wasm_bindgen::prelude::*;
//
// Intersection point between two links
//
#[wasm_bindgen]
#[derive(Copy, Clone)]
pub struct LinkIntersection {
intersection_x: f64,
intersection_y: f64,
link_1_index: u... | Rust | 0 |
from tkinter import *
from tkinter import messagebox
def tell_weather() :
import requests, json
api_key = "api_key"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = city_field.get()
complete_url = base_url + "appid =" + api_key + "&q =" + city_name
response = requests.get(complete_ur... | Python | 1 |
let pair_account = Self::get_pair_id(assets);
let asset_out_reserve = T::Currency::free_balance(assets.asset_out, &pair_account);
let asset_in_reserve = T::Currency::free_balance(assets.asset_in, &pair_account);
ensure!(asset_out_reserve > amount, Error::<T>::InsufficientPoolAssetBalance);
ensure!(
amount... | Rust | 0 |
ead_formula,
byzantium_formula,
difficulty_bomb,
skip_pow_verification,
)),
_ => bail!("unsupported consensus engine"),
})
}
use bytes::{Bytes, IntoBuf};
use futures::{future, Async, Future, Poll};
use futures::future::Either;
use h2;
use http;
use hyper::{self, b... | Rust | 0 |
(f2, textvariable = Lead45, width = "10", relief="solid").place(x = 80, y = 100)
Leada3 = Entry(f2, textvariable = Lead46, width = "10", relief="solid").place(x = 160, y = 100)
name3 = Label(f2, text = "Ends: Bar4", font="none 8 bold", fg="blue").place(x = 10,y = 130)
Leada0 = Entry(f2, textvariable = Lead47, width = "... | Python | 1 |
arning)]
if sys.py3kwarning:
deprecations += [
("classic (int|long) division", DeprecationWarning),
("coerce.. not supported", DeprecationWarning),
(".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
with test_support.check_warnings(*deprecations):
... | Python | 1 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from PIL import Image
import time
from reddit import getTopPostsToday
def getTitleScreenShot(url, filename):
driver = ... | Python | 1 |
ogg) fn read_properties<R>(
data: &mut R,
first_page: &Page,
) -> Result<VorbisProperties>
where
R: Read + Seek,
{
let first_page_abgp = first_page.abgp;
// Skip identification header
let first_page_content = &mut &first_page.content()[7..];
let version = first_page_content.read_u32::<LittleEndian>()?;
let c... | Rust | 0 |
from typing import Tuple
import bpy
from .syncedObjects import initSyncedObjects
from .shared import setDropDownOperatorAndIcon, removeDropDownOperatorAndIcon
from .syncClient import connectToWebsocket, disconnectFromWebsocket, isConnectedToWs
from ..utils.util import ShowMessageBox
class StartSyncOperator(bpy.types.O... | Python | 1 |
_class__.__name__ == "EmailAddressRelatedToIncident"
]
)
== 9
)
## - 1 EmailMessage entity
assert ( # noqa: S101
len(
[
entity
for entity in entities
if entity.__class__.__name__ == "EmailMessage"
]
... | Python | 1 |
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
username = models.EmailField(unique=True)
first_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
USERNAME_FIELD = "username"
RE... | Python | 1 |
# flake8: noqa: WPS102
from abc import abstractmethod
from types import TracebackType
from typing import Any, Protocol, TypeVar, runtime_checkable
from typing_extensions import Self
from retejo.core.entities import Method, Request, Response
_MethodResultT = TypeVar("_MethodResultT")
_MethodT_contra = TypeVar("_Metho... | Python | 1 |
# 红绿灯识别+道路识别 - By: 谢青桦 @kelecn - 周四 一月 29 2021
import sensor, image, time, math
from pyb import UART
import json
import ustruct
#white_threshold_01 = ((95, 100, -18, 3, -8, 4)); #白色阈值
light_threshold = [(59, 100, 26, 127, -128, 127),(59, 100, -128, -40, -128, 127)]; #0无数据 1红灯 2绿灯 4黄灯(59, 100, -128, 127, 28, 127)
ro... | Python | 1 |
", "en"])?;
assert_eq!("el stringo", l.string(ftest::MessageIds::StringName as u64)?.to_str()?);
assert_eq!("el stringo 2", l.string(ftest::MessageIds::StringName2 as u64)?.to_str()?);
Ok(())
}
#[test]
fn lookup_es_419_fallback() -> Result<(), LookupStatus> {
let icu_data = ... | Rust | 0 |
[1], s2);
} else {
assert!(sizes[0] >= s1);
assert!(sizes[1] >= s2);
assert_eq!(sizes[0] + sizes[1], a.max(s1 + s2));
}
if sizes[0] != s1 &&... | Rust | 0 |
nwrap();
let metrics = raster.get_metrics(config.completion_font_size, dpi);
(metrics.ascender, metrics.descender)
};
let height = (ascender - descender) as u32 + 2 * config.completion_line_padding;
let mut origin = relative_origin;
if options.len() == 0 {
... | Rust | 0 |
from datetime import datetime
from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field
class Memory(BaseModel):
"""记忆模型"""
user_message: str
ai_response: str
timestamp: str
similarity: Optional[float] = None
topic: Optional[str] = None
def __str__(self) -> str... | Python | 1 |
assert_eq!(email.to_uri(), String::from("mailto:<EMAIL>"));
}
// ------------------------------------------------------------------------------------------------
fn expect(address: &str, error: Error, test_case: Option<&str>) {
if let Some(test_case) = test_case {
println!(">> test... | Rust | 0 |
ominator: 0,
};
/// Instantiate a TrustThreshold with the given denominator and
/// numerator.
///
/// The constructor succeeds if long as the resulting fraction
/// is in the range`[0, 1)`.
pub fn new(numerator: u64, denominator: u64) -> Result<Self, Error> {
// The two parameters ... | Rust | 0 |
import numpy as np
from ..random_component import RandomComponent
from .subepisoded_reference_generator import SubepisodedReferenceGenerator
class LaplaceProcessReferenceGenerator(SubepisodedReferenceGenerator):
"""
Reference Generator that generates a reference for one state by a Laplace Process with the ch... | Python | 1 |
#!/usr/bin/python3
# Generates a .dart main file that imports every possible
# file from all packages in `.packages`, obeying some blacklists.
import re
import os
# place your own
BLACKLISTS = {
'sky_engine',
('intl', 'intl_browser.dart'),
('intl', 'date_symbol_data_http_request.dart'),
('matcher', 'mirror_ma... | Python | 1 |
p();
let proj = Projection::orthographic(
-1280.0 / 2.0,
1280.0 / 2.0,
-720.0 / 2.0,
720.0 / 2.0,
0.1,
100.0,
);
let view = gatherer_calc_view_matrix(camera_transform);
let mvp = proj.as_matrix() * view;
l... | Rust | 0 |
t has claimed
/// the slot)
#[serde(default)]
pub device_usage: HashMap<String, String>,
/// This is a placeholder for eventual RBAC support
#[serde(default = "default_rbac")]
pub rbac: String,
}
/// Get Instances for a given namespace
///
/// Example:
///
/// ```no_run
/// use akri_shared::ak... | Rust | 0 |
self.pc as isize) - 10) as usize);
let high: usize = std::cmp::min(MEMORY_LENGTH_NBYTES - 1, (self.pc as usize) + 10);
writeln!(f, "Sample of memory around PC: (0x{:2x} to 0x{:2x}):", low, high)?;
for i in low..=high {
writeln!(f, " 0x{:2x}: 0x{:x}", i, self.memory[i])?;
}
... | Rust | 0 |
DList())
previous_vehicle_ids = set(self.env.vehicle_ids)
# find new veh in map
new_vehicle_ids = current_vehicle_ids - previous_vehicle_ids
for vehicle_id in new_vehicle_ids:
self.env.vehicles[vehicle_id] = Vehicle(
vehicle_id,
self.env.sumo,... | Python | 1 |
if pubkeys.is_empty() {
return false;
}
match self.point.as_ref() {
Some(point) => point.fast_aggregate_verify(msg, pubkeys),
None => false,
}
}
/// Verify that `self` represents an aggregate signature where all `pubkeys` have signed their
/... | Rust | 0 |
def valid_permutations(prog, permutations=[], stack=[], start=False):
"""
Takes the prog, and returns valid permutation such that the final output
shape remains same. Mainly permuate the operands in union and intersection
open"""
for index, p in enumerate(prog):
if p["type"] == "draw":
... | Python | 1 |
y {
buffer_offset: 0,
buffer_width: row_pitch / (stride as u32),
buffer_height: dims.height as u32,
image_layers: i::SubresourceLayers {
aspects: f::Aspects::COLOR,
level: 0,
layers: 0..1,
},
image_offset: ... | Rust | 0 |
NamedFile> {
NamedFile::open(Path::new("ui/").join(file)).ok()
}
<filename>git-repository/src/easy/mod.rs<gh_stars>0
//! ### Which `Easy*` is for me?
//!
//! * Use `Easy*Exclusive` when the underlying `Repository` eventually needs mutation, for instance to update data structures
//! - This is useful for long-run... | Rust | 0 |
import graphene
from graphene_django import DjangoObjectType
from .models import management
class ManagementType(DjangoObjectType):
class Meta:
model = management
fields = '__all__'
class Query(graphene.ObjectType):
all_managements = graphene.List(ManagementType)
management_by_id = graphen... | Python | 1 |
]
/// Wraps the provided function with the initialization and finalization for PyO3 Asyncio
///
/// This function **_MUST_** be called from the main thread.
///
/// # Arguments
/// * `py` - The current PyO3 GIL guard
/// * `f` - The function to call in between intialization and finalization
///
/// # Examples
///
/// `... | Rust | 0 |
by(id=id).first()
products =supplier.products.all()
return render_template("customer_check_supplier_products.html",products=products,supplier=supplier)
@app.errorhandler(404)
def page_not_found(e):
template = '''
{%% block body %%}
<div class="center-content error">
<h1>哇哦,This pag... | Python | 1 |
class_name=class_name if class_name != "全部" else None,
subject=subject if subject != "全部" else None,
exam_type=exam_type if exam_type != "全部" else None
)
if not grades:
messagebox.showwarning("警告", "没有找到符合条件的成绩数据")
return
for widget in s... | Python | 1 |
N + "\n\n预备原材料生成完毕!" + Fore.RESET)
# def amb_to_pdf(self, file_toml, outside_flg):
# """ 从 amb 文件夹合成 PDF 文件 """
# # 0.准备路径相关
# dir_amb = os.path.split(file_toml)[0]
# if outside_flg:
# out_file = os.path.join(os.path.split(dir_amb)[0], self.settings.name+'.pdf')
# ... | Python | 1 |
which fails.
harness.trigger_ping().await;
harness.expect_ping_send_not_ok().await;
}
// Health checker should disconnect from peer after tolerated number of failures
harness.expect_disconnect(peer_id).await;
};
block_on(future::join(health_checker.start(), test... | Rust | 0 |
your current earnings!"
if total_kryon_earned > 0:
result_message += f" and Ꝿ{total_kryon_earned} Kryon"
result_message += "."
await event.edit(result_message, buttons=None)
await give_xp(user_id, total_coins_earned // 1000 + total_kryon_earned * 10)
del acti... | Python | 1 |
| p.id == id).cloned() {
let mut msgs = vec![MessageVariant::LeftGame { name: player.name }];
if self.landlord == Some(id) {
self.landlord = None;
}
self.players.retain(|p| p.id != id);
msgs.extend(self.num_players_changed()?);
Ok(m... | Rust | 0 |
m)
def treat_page_and_item(self, page: pywikibot.page.BasePage,
item: pywikibot.page.ItemPage) -> None:
"""Treat page together with its item (if it exists).
Must be implemented in subclasses.
"""
raise NotImplementedError(f'Method {type(self).__name__}.'... | Python | 1 |
" />
import foo = require('foo');
"#:[
{
line: 2,
col: 0,
message: TripleSlashReferenceMessage::Unexpected,
}],
r#"/// <reference path="foo" />"#: [
{
col: 0,
message: TripleSlashReferenceMessage::Unexpected,
}],
r#"/// <reference types="fo... | Rust | 0 |
_golden",
note = "Verifies all file paths in bootfs."
)]
pub struct ScrutinyBootfsCommand {
/// path to ZBI image file that contains bootfs.
#[argh(option)]
pub zbi: String,
/// path(s) to golden file(s) for verifying bootfs paths.
#[argh(option)]
pub golden: Vec<String>,
/// path to sta... | Rust | 0 |
ult folders for history and screenshots if they don't exist"""
global addon_prefs
try:
# Get preferences - first try using the global reference
if not addon_prefs:
try:
# If the global variable isn't set yet, try to get it directly
addon_prefs = b... | Python | 1 |
z_strides[1],
z_strides[2],
out.stride(0),
out.stride(1),
out.stride(2),
dt_softplus,
tie_hdim,
BLOCK_SIZE_M,
num_warps=num_warps,
)
if not has_heads:
out = out.squeeze(1)
return out
def sel... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, Command
class CalendarEvent(models.Model):
_inherit = 'calendar.event'
def _get_lead_values(self, partner):
lead_values = super()._get_lead_values(partner)
visitor_sudo... | Python | 1 |
assert_eq!( got, vec![ 1, 2 ] );
}
//
#[test]
fn left_index()
{
println!( "empty vector" );
let mut src : left_index<u8> = left_index::default();
src.ins( 1 );
let got = src.call();
assert_eq!( got, None );
println!( "filled vector, not matches" );
let mut src : left_index<u8> = left_index::default(... | Rust | 0 |
await task
except asyncio.CancelledError:
pass
# Close connection pools
await self.connection_pool_manager.shutdown()
# Close async pool
if self.async_pool:
# AioPool doesn't have cl... | Python | 1 |
{
setup();
select_and_then_compare(
r#"$['single\'quote']"#,
json!({"single'quote":"value"}),
json!(["value"]),
);
select_and_then_compare(
r#"$["double\"quote"]"#,
json!({"double\"quote":"value"}),
json!(["value"]),
);
}
//#[test]
pub fn all_filter(... | Rust | 0 |
import streamlit as st
st.set_page_config(page_title="TQmax/TSL 계산기", layout="centered", page_icon="📈")
st.image("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Medical_icon.svg/1200px-Medical_icon.svg.png", width=80)
st.title("📊 TQmax / TSL 계산기")
unit_factors = {
"mg": 1000,
"µg": 1,
"ng": 0... | Python | 1 |
# -*- Mode: Python -*- vi:si:et:sw=4:sts=4:ts=4:syntax=python
#
# Copyright (c) 2016,Thibault Saunier <thibault.saunier@osg.samsung.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; ... | Python | 1 |
;
let mut node = Some(node);
while let Some(n) = node.take() {
{
let key = match n.value {
NCValue::Text(_) => RuleKeyBorrow::Text,
NCValue::Element(ref e) => RuleKeyBorrow::ElementBorrow(e),
};
current =... | Rust | 0 |
image_path.replace('bad', 'mask')
if os.path.exists(mask_path) and 'good' not in image_path:
msk = Image.open(mask_path).convert("L")
for i in range(5):
left = i * part_width
right = (i + 1) * part_width if i < 4 else width
cropped_msk = ms... | Python | 1 |
# coding: utf-8
"""
openapi 3.1.0 sample spec
sample spec for testing openapi functionality, built from json schema tests for draft2020-12 # noqa: E501
The version of the OpenAPI document: 0.0.1
Generated by: https://github.com/openapi-json-schema-tools/openapi-json-schema-generator
"""
from unit_tes... | Python | 1 |
from typing import Tuple
import cv2
import numpy as np
from PIL import Image
from core.perception.ocr.interface import OCRInterface
from core.types import XYXY
from core.utils.geometry import crop_pil
from core.utils.text import fuzzy_ratio
BADGE_PRIORITY = {"EX": 5, "G1": 4, "G2": 3, "G3": 2, "OP": 1, "UNK": 0}
B... | Python | 1 |
.
/// Unlike [`bond`] or [`unbond`] this function does not impose any limitation on the amount
/// that can be added.
///
/// The dispatch origin for this call must be _Signed_ by the stash, not the controller and
/// it can be only called when [`EraElectionStatus`] is `Closed`.
///
/// Emits `Bonded`.
... | Rust | 0 |
import numpy as np
import deca
def calcular_rayos(pixelL, pixelR, CAML, CAMR):
pixelL = np.array([pixelL[0], pixelL[1], 1])
q_pixelL = np.linalg.inv(CAML.matrix).dot(pixelL)
q_worldL = np.linalg.inv(CAML.rot).dot(q_pixelL) - np.linalg.inv(CAML.matrix).dot(CAML.tras)
dirL = CAML.rot.T.dot(q_pixelL)
... | Python | 1 |
ator<Item = Option<Location>> + 'a> {
match job {
Job::Single(single) => Box::new(single.places.iter().map(|p| p.location)),
Job::Multi(multi) => Box::new(multi.jobs.iter().flat_map(|j| j.places.iter().map(|p| p.location))),
}
}
fn get_avg_profile_costs(fleet: &Fleet) -> HashMap<usize, Costs> {... | Rust | 0 |
e
data.iloc[sub_pct, data.columns.get_loc(pct)] = \
100 * data[yr].iloc[sub_pct] / data[yr].iloc[sub_pct].sum()
sub_pct = []
if snap.level == 2: sub_pct.append(r)
def check_current(dt, logger, **kwargs) -> bool:
"""
Check current time against T-1
"""
t_1... | Python | 1 |
> {}
impl<'data, 'file> ObjectSymbolTable<'data> for SymbolTable<'data, 'file> {
type Symbol = Symbol<'data, 'file>;
type SymbolIterator = SymbolIterator<'data, 'file>;
fn symbols(&self) -> Self::SymbolIterator {
SymbolIterator {
inner: map_inner!(
self.inner,
... | Rust | 0 |
// #[prost(message, optional, tag="1")]
// pub proof: ::core::option::Option<::tendermint_proto::crypto::ProofOps>,
// }
// - Vec<u8>: RawMerkleProof is not explicitly used but, serialized as Vec<u8>, it is
// included in all handshake messages that require proofs (i.e. all except... | Rust | 0 |
# -*- encoding: utf-8 -*-
# Copyright (c) 2023-2024 Huawei Cloud Computing Technology Co., Ltd. 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.o... | Python | 1 |
fn run() -> Result<()> {
let opt = parse_args()?;
let mut svg_buf = Vec::default();
if let Some(ref filename) = opt.input {
File::open(filename)
.chain_err(|| "Failed to open input")?
.read_to_end(&mut svg_buf)
.chain_err(|| "Failed to read input")?;
} el... | Rust | 0 |
rtex_dtype)
# Fill the structured array
attrs = {
'x': positions[:, 0], 'y': positions[:, 1], 'z': positions[:, 2],
'nx': np.zeros(num_vertices), 'ny': np.zeros(num_vertices), 'nz': np.zeros(num_vertices),
'f_dc_0': shs[:, 0], 'f_dc_1': shs[:, 1], 'f_dc_2': shs[:, 2],
'opaci... | Python | 1 |
td::error::Error>> {
// getting certificate from disk
let cert = include_str!("../../certs/client.pem");
let key = include_str!("../../certs/client.key");
// creating identify from key and certificate
let id = tonic::transport::Identity::from_pem(cert.as_bytes(), key.as_bytes());
// importing ou... | Rust | 0 |
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"
/>
</svg>
}
}
pub fn directory_icon(class: &'static ... | Rust | 0 |
import argparse
from pathlib import Path
import cv2
from tqdm import tqdm
def extract_frames(video_path: str, output_dir: str):
"""
Extracts all frames from a video file and saves them as PNGs in an output directory.
Args:
video_path (str): Path to the input video file.
output_dir (str):... | Python | 1 |
message and compare it ith the original
fn test(message: ClientMessage) {
let mut buf: Vec<u8> = Vec::new();
message.clone().serialize_into_writer(&mut buf).unwrap();
let message_out = ClientMessage::deserialize_from_reader(&mut buf.as_slice()).unwrap();
assert_eq!(message, message_o... | Rust | 0 |
struct BlindSignature {
/// A
pub(crate) a: G1,
/// e
pub(crate) e: Fr,
/// s
pub(crate) s: Fr,
}
impl BlindSignature {
/// 1 or more messages have been hidden by the signature recipient. The remaining
/// known messages are in `messages`. The generator to which they correspond is in `... | Rust | 0 |
Box::<pg_sys::TimeLineHistoryCmd>::alloc_node(PgNode::TimeLineHistoryCmd)
}
pub fn makeSQLCmd() -> PgBox<pg_sys::SQLCmd> {
PgBox::<pg_sys::SQLCmd>::alloc_node(PgNode::SQLCmd)
}
pub fn makeTriggerData() -> PgBox<pg_sys::pg11_specific::TriggerData> {
PgBox::<pg_sys::pg11_specific::Trigger... | Rust | 0 |
import pytest
from mlflow.exceptions import MlflowException
from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore
def test_log_batch_internal_error(store: SqlAlchemyStore):
()
def test_log_batch_params_max_length_value(store: SqlAlchemyStore, monkeypatch):
()
def test_log_param_max_length_val... | Python | 1 |
from filamentcolors.bluesky import parse_hashtags, parse_mentions, parse_urls
def test_parse_single_url():
text = "This is a test of the http://example.com URL parser."
assert parse_urls(text) == [{"start": 22, "end": 40, "url": "http://example.com"}]
def test_parse_multiple_urls():
text = "This is a te... | Python | 1 |
import unittest
import os
from modules.entities.apk import Apk
from modules.entities.source import Source
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
class SourceTest(unittest.TestCase):
def test_initializes_from_file(self):
source = Source(input_file=os.path.join(THIS_DIR, 'resources/sample... | Python | 1 |
nnerStorage::File(i) => i.rename(user, from, to).await,
}
}
async fn rmd<P: AsRef<Path> + Send + Debug>(&self, user: &Option<User>, path: P) -> Result<()> {
slog::info!(self.log(user, &path), "Client requested to remove a directory");
match &self.inner {
InnerStorage::Cloud(... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.