text string | label_name string | labels int64 |
|---|---|---|
params.message, ¶ms.ring, &output_commitment);
match result {
Err(Error::InvalidSignature) => {} // This is expected.
_ => panic!(),
}
}
}
#[test]
// `verify` should reject a signature if the key image is n... | Rust | 0 |
Entry<UserId>>> {
Ok(self.0.database.connect()?.query(
"SELECT discord_user_id, is_unverify, last_updated FROM user_history \
WHERE roblox_user_id = ?1 \
ORDER BY rowid DESC LIMIT ?2", (user, limit)
).get_all::<(UserId, bool, SystemTime)>()?.iter().rev()
... | Rust | 0 |
#!/usr/bin/python3
"""
Copyright (c) 2022, Ian Santopietro
All rights reserved.
This file is part of RepoLib.
RepoLib 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, either version 3 of the License, or
(... | Python | 1 |
R"));
//Verify all
let all: HashMap<String, String> = core.storage_getall();
assert_eq!(all.get(&String::from("FOO")).unwrap().clone(), String::from("BAR"));
assert_eq!(all.get(&String::from("PIPPO")).unwrap().clone(), String::from("PLUTO"));
//Unset value
core.value_unse... | Rust | 0 |
clients: TokenStream,
servers: TokenStream,
}
impl ServiceGenerator {
fn new(builder: Builder) -> Self {
ServiceGenerator {
builder,
clients: TokenStream::default(),
servers: TokenStream::default(),
}
}
}
impl prost_build::ServiceGenerator for Servi... | Rust | 0 |
pe_3d[:, index2] -= (shape_3d[:, index2] - mean_in) * p1
shape_3d = shape_3d.reshape((68, 3))
return shape_3d
def norm_input_face(shape_3d):
scale = 1.6 / (shape_3d[0, 0] - shape_3d[16, 0])
shift = - 0.5 * (shape_3d[0, 0:2] + shape_3d[16, 0:2])
shape_3d[:, 0:2] = (shape_3d[:, 0:2] + shift) * scale... | Python | 1 |
o avoid floating point errors
# print(MW)
if utilities.handle_rounding_error(MW, 'mw') > 200: # decimal points for floating point errors
a = 2.5737
b = 1.0133
c = -3.573
d = 2.464
e = -3.6701
f = 1.96312
g = -4.0377
h = 2.6568
i = 1.60... | Python | 1 |
import os
import random
import numpy as np
from PIL import Image
from torchvision.datasets.vision import VisionDataset
class DogsVsCatsData(VisionDataset):
label_to_int = {"cat": 0, "dog": 1}
def __init__(self, root, transform=None, target_transform=None, train=True):
super().__init__(root, transfo... | Python | 1 |
) {
for unrendered in self.unrendered.iter() {
unrendered.fetch_result(fetcher, seq, score, bind_var_keys, result);
}
self.visible
.fetch_result(fetcher, seq, score, bind_var_keys, result);
}
fn get_aggregate_funs(&self, funs: &mut Vec<Option<(AggregateFun, O... | Rust | 0 |
oint-get-track
pub fn get_track(&self, id: &str) -> Result<Arc<Track>, Error> {
let request = self
.get(format!("v1/tracks/{}", id))?
.query("market", "from_token");
let result = self.load(request)?;
Ok(result)
}
}
/// Library endpoints.
impl WebApi {
// http... | Rust | 0 |
0a\xfa2\xc0\xce\x8e\xc7\xfc\
\x08E\x95F8\x1e7m\x1c\x87\x84\xc7%o\xa0\xfc\
\x91\xb4w\xea,\x97\x91\xe8\x19\x1c\xe4\xf9\x97TA\x07\
%\xfb\xb8\x0e'\x0e\x22\x9b;\xf4\xf6|\x80\xce\x06o\
&~\x13\x98\x91\xa8I\xc3Uh\x17\xb4O\xe1\xffK\
;\x83P$bO\xe06\xb4`\xda\x81\xf8\xfbr7\
!1\xff'\xca\xd4\xce\xaa\xc9\xcfJ(\xb3\xdd\xf5B\
i-\xd2ia\... | Python | 1 |
OpenDrain>>, Delay) {
let cp = CorePeripherals::take().unwrap();
let mut p = Peripherals::take().unwrap();
let mut rcc = p.RCC.configure().freeze(&mut p.FLASH);
let gpioa = p.GPIOA.split(&mut rcc);
let mut pa8 = cortex_m::interrupt::free(move |cs| gpioa.pa8.into_open_drain_output(cs));
// Pul... | Rust | 0 |
x80000000,
}}
STRUCT!{struct D3D11_VIDEO_PROCESSOR_RATE_CONVERSION_CAPS {
PastFrames: UINT,
FutureFrames: UINT,
ProcessorCaps: UINT,
ITelecineCaps: UINT,
CustomRateCount: UINT,
}}
ENUM!{enum D3D11_CONTENT_PROTECTION_CAPS {
D3D11_CONTENT_PROTECTION_CAPS_SOFTWARE = 0x1,
D3D11_CONTENT_PROTECTIO... | Rust | 0 |
# Hydrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2023 Dan <https://github.com/delivrance>
# Copyright (C) 2023-present Hydrogram <https://hydrogram.org>
#
# This file is part of Hydrogram.
#
# Hydrogram is free software: you can redistribute it and/or modify
# it under the terms o... | Python | 1 |
from Locators.iPhone15BlueCartLocators import iPhone15_blue_cart_locators
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class iPhone_red_refurbished_utilities:
def __init__(self,driver):
self.driver = driver
def iPhone15_blue... | Python | 1 |
(self))]
async fn get_kv(&self, key: &str) -> Result<GetKVReply, MetaError> {
let res = self
.consistent_read(GetKVReq {
key: key.to_string(),
})
.await?;
Ok(res)
}
#[tracing::instrument(level = "debug", skip(self))]
async fn mget_kv(... | Rust | 0 |
) else api.jit(func)
exported = _export.export(
jit_func,
platforms=(self.default_jax_backend(),),
disabled_checks=tuple(
_export.DisabledSafetyCheck.custom_call(target)
for target in allow_unstable_custom_call_targets)
)(*args_specs)
module_str = str(exported.mlir_module(... | Python | 1 |
the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the speci... | Rust | 0 |
e, Serialize, Debug, Clone)]
#[serde(untagged)]
pub enum SubscriptionData {
Announcements(AnnouncementsData),
Book(BookData),
AtlasPriceIndex(AtlasPriceIndexData),
AtlasPriceRanking(Vec<AtlasPriceRankingData>),
EstimatedExpirationPrice(EstimatedExpirationPriceData),
GroupedBook(GroupedBookData),... | Rust | 0 |
pso::FrontFace::CounterClockwise => vk::FrontFace::CounterClockwise,
}
}
pub fn map_comparison(fun: pso::Comparison) -> vk::CompareOp {
use hal::pso::Comparison::*;
match fun {
Never => vk::CompareOp::Never,
Less => vk::CompareOp::Less,
LessEqual => vk::CompareOp::... | Rust | 0 |
rt_eq!(is_list_word("10)"), true);
assert_eq!(is_list_word("9999)"), true);
assert_eq!(is_list_word("9999)."), false);
}
#[test]
fn should_unindent() {
assert_eq!(unindent(" 1\r\n 2"), "1\r\n2");
assert_eq!(unindent(" 1\n 2"), " 1\n2");
assert_eq!(unindent(" 1\n 2"), "1\n 2");
assert_... | Rust | 0 |
import os
import tarfile
from github3 import login
token = os.getenv('GITHUB_TOKEN')
gh = login(token=token)
repo = gh.repository('gamechanger', 'dusty')
version = os.getenv('VERSION')
prerelease = os.getenv('PRERELEASE') == 'true'
release_name = version
release = repo.create_release(version, name=release_name, pre... | Python | 1 |
this by always adding "end" to the
current rule, which is enough in practice.
"""
rules = []
rule = []
for line in list(input_text.splitlines()) + [""]:
if rule and not line.startswith(" "):
rules.append(rule)
rule = []
... | Python | 1 |
ons in one image
:param im_array: [b=1 c h w] in rgb
:param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
:param class_names: list of names in imdb
:param scale: visualize the scaled image
:return:
"""
import cv2
import random
color_white = (255, 255, 255)
... | Python | 1 |
self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by... | Python | 1 |
nize(info.caption)
batch.append((info, l_tokens, g_tokens, t5_tokens))
if len(batch) >= batch_size:
batches.append(batch)
batch = []
if len(batch) > 0:
batches.append(batch)
# iterate batches: call text encoder and cache outputs ... | Python | 1 |
(hsts_val, str):
m = re.search(r"max-age=(\d+)", hsts_val, re.IGNORECASE)
max_age = int(m.group(1)) if m else 0
if max_age < 31536000:
reasons.append("max-age < 31536000")
if "includesubdomains" not in hsts_val.lower():
... | Python | 1 |
<dyn Iterator<Item=Self::Item> + 'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a,T> IntoIterator for &'a mut $svec<T> {
type Item = &'a mut T;
type IntoIter = Box<dyn Iterator<Item=Self::Item> + 'a>;
fn into_... | Rust | 0 |
f.ref_status = False
return
use_time = 0
for time in json_data['activity']:
use_time = use_time + time['hours_played']
self.teeRankRing.setRange(0, json_data["points"]["total"])
self.teeRankRing.setValue(json_data["points"]["points"])
self.teeRankRing.set... | Python | 1 |
import numpy
from Augmentations import WrapText, CustomSequenceAugmentations, AffineTransform
from Augmentations.Augmentations import Transformation3D
from Texture import Painter, TextureMixer
class TextImageAugmentations:
def __init__(self, args):
self.augmentations = []
self.layoutAugmentation ... | Python | 1 |
PYPI_URL = "https://pypi.org/pypi/kuzu/json"
CMAKE_KEYWORD = "project(Kuzu VERSION "
CMAKE_SUFFIX = " LANGUAGES CXX C)\n"
import urllib.request
import json
import os
import sys
def main():
try:
from packaging.version import Version
except ImportError:
from distutils.version import LooseVersion... | Python | 1 |
#!/usr/bin/env python
# coding=utf-8
from pwn import remote, log
from hashlib import sha256
from itertools import product
def enc(m='a'*16):
r.sendlineafter('> ', '1')
r.sendlineafter(': ', m)
res = r.recvline().strip()
return res[:32].decode('hex'), res[32:].decode('hex')
def getflag():
r.sendl... | Python | 1 |
pub timetolive: uint32_t,
pub ppid: uint32_t,
pub context: uint32_t,
pub sinfo_flags: uint16_t,
pub sid: uint16_t,
pub act_flags: uint16_t,
pub auth_keyid: uint16_t,
pub holds_key_ref: uint8_t,
pub msg_is_complete: uint8_t,
pub some_taken: uint8_t,
pub sender_all_done: uint8_t,
... | Rust | 0 |
e used as arguments of `atLeast(..., sigmaProp(boolExpr), ...)` operation.
* During execution results to either `TrueProp` or `FalseProp` values of SigmaProp type.
*/
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct BoolToSigmaProp {
/// Expr of type SBoolean
pub input: Box<Expr>,
}
impl BoolToSigmaProp {
... | Rust | 0 |
ow up as a drive with 0 space free when there is no card inserted.
free_bytes = ctypes.c_longlong(0)
if ctypes.windll.kernel32.GetDiskFreeSpaceExA(drive.encode("ascii"), ctypes.byref(free_bytes), None, None) == 0:
continue
if free_bytes.value < 1:
... | Python | 1 |
2t-small-librispeech-asr")
model.to(torch_device)
processor = self.default_processor
input_speech = self._load_datasamples(1)
input_features = processor(input_speech, return_tensors="pt").input_features.to(torch_device)
generated_ids = model.generate(input_features)
ge... | Python | 1 |
WS",
// "credentials": {
// "id": "https://example.com/issuer/123#ovsDKYBjFemIy8DVhc-w2LSi8CvXMw2AYDzHj04yxkc",
// "type": "JsonWebKey2020",
// "controller": "https://example.com/issuer/123",
// "publicKeyJwk": {
// "kty": "OKP",
// ... | Rust | 0 |
USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
use crate::Float;
pub struct Location {
pub city: String,
pub state: String,
pub country: String,
pub source: String,
pub wmo: String,
pub latitude: Float,
pub longitude: Float,
pub timezone: Float,
pub elevation: Float
}
impl Location{
... | Rust | 0 |
HttpPart,
Interaction,
matchingrules,
Pact,
PACT_RUST_VERSION,
ReadWritePact,
RequestResponseInteraction,
RequestResponsePact
};
use crate::models::file_utils::with_read_lock;
use crate::models::generators::{Generators, generators_to_json};
use crate::models::json_utils::{hash_json, json_to_string};
use... | Rust | 0 |
as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `RMT_TX_SIM_CH1`"]
pub type RMT_TX_SIM_CH1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RMT_TX_SIM_CH1`"]
pub struct RMT_TX_SIM_CH1_W<'a> {
w: &'a mut W,
}
impl<'a> RMT_TX_SIM_CH1_W<'a> {
#[doc = r"Sets the field bit"]
#[in... | Rust | 0 |
"""Test fits plugin functionality."""
import pytest
import imageio.v2 as iio
from imageio.core import Request
import numpy as np
from conftest import deprecated_test
fits = pytest.importorskip("astropy.io.fits", reason="astropy is not installed")
@deprecated_test
def setup_module():
# During this test, preten... | Python | 1 |
str_update_ind(ht: *mut HashTable, key: *const c_char, len: usize, pData: *mut zval) -> *mut zval;
fn _zend_hash_str_add(ht: *mut HashTable, key: *const c_char, len: usize, pData: *mut zval) -> *mut zval;
fn _zend_hash_str_add_new(ht: *mut HashTable, key: *const c_char, len: usize, pData: *mut zval) -> *mut zva... | Rust | 0 |
pability `GeometryStreams`.
///
/// # Safety
/// This instruction must only be used when multiple streams are present.
#[spirv_std_macros::gpu_only]
#[doc(alias = "OpEndStreamPrimitive")]
#[inline]
pub unsafe fn end_stream_primitive<const STREAM: i64>() {
asm! {
"%i64 = OpTypeInt 64 1",
"%stream = O... | Rust | 0 |
#[serde(default)]
pub default_comments: Vec<CommentsConfig>,
#[serde(default)]
pub comments: Vec<CommentsConfig>,
#[serde(default)]
pub styles: StylesConfig,
}
//! Find the sum of all the primes below two million.
use crate::utils::primes::Primes;
fn solve_for(bound: u64) -> u64 {
Primes::<u64>... | Rust | 0 |
())
}
/// Get a specific stored message, if it exists.
pub async fn get_message(
conn: &sqlx::Pool<sqlx::Postgres>,
id: i32,
) -> anyhow::Result<Option<MediaGroup>> {
let message = sqlx::query!(
"SELECT id, inserted_at, message, sources FROM media_group WHERE id = $1... | Rust | 0 |
ching, closing, env.cube.pose.sp.p)
grasp_pose.p = torch.tensor([env.disk_x - env.cube_r, env.disk_y, env.cube.pose.sp.p[2]])
reach_pose = grasp_pose * sapien.Pose([0.05, 0, 0])
res = planner.move_to_pose_with_screw(reach_pose)
pull_pose = grasp_pose * sapien.Pose([-0.18, 0, 0])
for i in range(... | Python | 1 |
s,
re: [0u8; DH_LEN],
rs: [0u8; DH_LEN],
c,
}
}
#[derive(Debug)]
pub enum Error {
Input,
Decrypt,
Dh,
}
#[cfg(test)]
mod test {
use crate::*;
extern crate alloc;
const PROT_NAME: &str = "Noise_IX_25519_ChaChaPoly_BLAKE2s";
#[test]
fn test_ix_snow() ... | Rust | 0 |
day_twelve::run();
day_thirteen::run();
day_fourteen::run();
day_fifteen::run();
},
_ => println!("Invalid day.")
}
println!("\n...done in {}ms", start.elapsed().as_millis());
}
mod day_one;
mod day_two;
mod day_three;
mod day_four;
mod day_five;
mod day_six;... | Rust | 0 |
ext": f"{xp_for_next}",
"progress": f"{progress:.2f}%"
}
@app.get("/zad5/skill/carpentry_skill")
def Zad5_Carpentry_skill():
level_data = skillsFF.carpentryLVL()
skill = "Carpentry"
level = level_data["level"]
xp_current = level_data["xp_current"]
xp_for_next = level_data["xp_for_nex... | Python | 1 |
t_file", "out_null", "out_err"]))
// STDERR
.arg(Arg::with_name("err_file")
.long("--err-file")
.takes_value(true))
.arg(Arg::with_name("err_null")
.long("--err-null"))
.arg(Arg::with_name("err_out")
.long("--err-out"))
.group(... | Rust | 0 |
# encoding: utf8
from __future__ import unicode_literals
from ...symbols import ORTH, LEMMA, POS, ADV, ADJ, NOUN
_exc = {}
for exc_data in [
{ORTH: "m.in.", LEMMA: "między innymi", POS: ADV},
{ORTH: "inż.", LEMMA: "inżynier", POS: NOUN},
{ORTH: "mgr.", LEMMA: "magister", POS: NOUN},
{ORTH: "tzn.", L... | Python | 1 |
#
# Copyright (c) 2019-2025, NVIDIA CORPORATION.
#
# 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 applicable law or ag... | Python | 1 |
import os
import joblib
import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report
from sentence_transformers import SentenceTransformer
def get_embeddings(data_dir, train_texts, test_texts):
... | Python | 1 |
import tkinter as tk
def increment():
current_value = int(label["text"])
label["text"] = str(current_value + 1)
def decrement():
current_value = int(label["text"])
label["text"] = str(current_value - 1)
def reset():
label["text"] = 0
def add10():
current_value = int(label["text"])
la... | Python | 1 |
lue') + 'DGC+M-Net created.')
else:
raise ValueError('check the model type [dgc, dgcm]')
model = nn.DataParallel(model)
model = model.to(device)
# Optimizer
optimizer = \
optim.Adam(filter(lambda p: p.requires_grad, model.parameters()),
lr=args.lr,
... | Python | 1 |
import os
import requests
from . import bilibili_schema
from . import prepare_env
from . import media_type
from . import etcs
def bilibili(i:dict)->list:
# Sourcer
# 1: api接口
_k = []
if "Path" in i : _path = i["Path"]
else: _path = "./assets/"
headers = {"User-Agent":"Mozilla/5.0"}
pages = ... | Python | 1 |
# https://github.com/coleifer/peewee
# pip install peewee
from peewee import *
# SQLite, MySQL, PostgreSQL을 지원하는 간단하고 표현이 풍부한 API를 가진 ORM
# 개인적으로 SQLAlchemy보다 선호한다
db = MySQLDatabase('test', user='root')
# SQLiteDatabase, MySQLDatabase, PostgreSQLDatabase 클래스를 지원
# 내부적으로는 각 데이터베이스의 driver를 통해 데이터베이스에 연결하므로, 아래의 코드 블럭을... | Python | 1 |
</p></body></html>"
label2 = "MrBayes Path:"
label3 = "<html><head/><body><p>If you don\'t have MrBayes, please <span style=\" font-weight:600; color:#ff0000;\">download</span>.</p></body></html>"
self.installStatus(flag, "start")
url = self.getURls("MrBayes")
... | Python | 1 |
:
"""
删除角色数据库操作
:param db: orm对象
:param role: 角色对象
:return:
"""
db.query(SysRole) \
.filter(SysRole.role_id == role.role_id) \
.update({SysRole.del_flag: '2', SysRole.update_by: role.update_by, SysRole.update_time: role.update_time})
@... | Python | 1 |
, totalSyncResend)
return {
"monitorResults": monitorResults,
"totalMessagesResend": totalMessagesResend,
"totalSyncResend": totalSyncResend,
}
if __name__ == "__main__":
folderName = "zFinalTestsV3"
results = []
# for each folder in the directory, get the number of time... | Python | 1 |
into(users).values(&user).get_result(conn)?;
return Ok(inserted_user.into());
}
}
Err(ServiceError::BadRequest("Invalid Invitation".into()))
})
}
}
//! Helper routines for re-implementing functions in Ruby and mruby.
pub mod m... | Rust | 0 |
);
let camera = Camera::new(
lookfrom,
lookat,
Vector3::new(0.0, 1.0, 0.0),
60.0,
(nx as f64) / (ny as f64),
0.1,
(lookat - lookfrom).length(),
);
for y in (0..ny).rev() {
for x in 0..nx {
let mut color = Vector3::new(0.0, 0.0, 0.0... | Rust | 0 |
gateway/fixtures/32b-account-and-u64-balance/transfer_return_code.wasm",
);
let correct_wasm_code = load_contract_code(&correct_wasm_path).unwrap();
new_test_ext_builder(50, ESCROW_ACCOUNT).execute_with(|| {
let _ = Balances::deposit_creating(&REQUESTER, 10_000_000_000);
assert_ok!(EscrowG... | Rust | 0 |
import enum
import uuid
from sqlalchemy import JSON, Boolean, Column, Enum, ForeignKey, Integer, String, Text, DateTime, func
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from app.db.base_class import Base
class DataSourceType(str, enum.Enum):
sql = "sql"
csv = "cs... | Python | 1 |
"""Wrapper around text2vec embedding models."""
from typing import Any, List, Optional
from langchain_core.embeddings import Embeddings
from pydantic import BaseModel, ConfigDict
class Text2vecEmbeddings(Embeddings, BaseModel):
"""text2vec embedding models.
Install text2vec first, run 'pip install -U text2... | Python | 1 |
れるか成れないか判定だぜ☆(^~^)!
///
/// Arguments
/// ---------
///
/// * `destinaion` -
/// * `callback` -
/// * `move_permission` - 成らずに一番奥の段に移動することはできません。
fn promote_pawn_lance<F1>(
phase_operation: &Box<dyn PhaseOperation>,
destination: &FireAddress,
callback: &mut F1,
... | Rust | 0 |
.about("warp-embed test server")
.arg(
Arg::with_name("listen")
.index(1)
.help("Listen host:port")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("prefix")
.short("p")
... | Rust | 0 |
mple_weight" not in fit_params
return super().fit(X, y, **fit_params)
clf = ClfWithoutSampleWeight()
pc_clf = CalibratedClassifierCV(clf)
with pytest.warns(UserWarning):
pc_clf.fit(X, y, sample_weight=sample_weight)
def test_calibration_with_fit_params_inconsistent_length(data):
... | Python | 1 |
checkpoint_file, checkpoint['epoch']))
if cfg.FP16.ENABLED:
lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(
optimizer.optimizer, cfg.TRAIN.LR_STEP, cfg.TRAIN.LR_FACTOR,
last_epoch=last_epoch
)
else:
lr_scheduler = torch.optim.lr_scheduler.MultiStepL... | Python | 1 |
if sp.len() < 4 {
panic!("Short string");
}
(
sp[0].to_string().trim().parse().ok().expect("pless input number"),
sp[1].to_string().trim().parse().ok().expect("pless input number"),
sp[2].to_string().trim().parse().ok().expect("pless input number"),
sp[3].to_string()... | Rust | 0 |
_msg: Self::Msg) -> Option<Self::Rsp> {
self.count += _msg;
None
}
fn stop(&mut self, _ctx: &mut Context<Self>) {
println!("Recorder sotpped");
}
}
#[tokio::main]
async fn main() {
let mut args = std::env::args();
let mut cocurrency = num_cpus::get();
if args.len() >=... | Rust | 0 |
)
doc = {"__group_ids": list(user_source.group_ids), "__group_names": list(user_source.group_names)}
user_adapter.update(user_source.user_id, doc)
for user_source in stream_user_sources(group_doc.get("removed_users", [])):
if group_doc["name"] in user_source.group_names or group_doc... | Python | 1 |
bErrorHandler>, PacketId),
/// Subscribed (SUBACK received with positive code)
Subscribed(Box<MsgHandler<M>>),
}
impl<M> SubState<M> {
/// Completes the subscription in case the packet ID matches the subscription's packet ID
pub fn try_complete(&mut self, res: &SubRes) -> bool {
*self = if let... | Rust | 0 |
olors, StandardToolMessageType, ToolFsmState};
use crate::document::DocumentMessageHandler;
use crate::input::InputPreprocessorMessageHandler;
use crate::layout::layout_message::LayoutTarget;
use crate::message_prelude::*;
use graphene::color::Color;
use std::collections::VecDeque;
#[derive(Debug, Default)]
pub stru... | Rust | 0 |
#!/usr/bin/env python3
import json
from TestHarness import Account, Cluster, Node, ReturnType, TestHelper, Utils, WalletMgr
from TestHarness.TestHelper import AppArgs
###############################################################
# light_validation_sync_test
#
# Test message sync for light validation mode.
#
# Thi... | Python | 1 |
# -*- Mode: Python -*-
# monitor client, win32 version
# since we can't do select() on stdin/stdout, we simply
# use threads and blocking sockets. <sigh>
import socket
import string
import sys
import thread
import md5
def hex_digest (s):
m = md5.md5()
m.update (s)
return string.join (
map (... | Python | 1 |
ing
col_map = mapping[col]
result_df[col] = df[col].map(col_map)
# Handle values not in mapping
if result_df[col].isna().any() and not df[col].isna().any():
max_val = max(col_map.values()) if col_map else 0
... | Python | 1 |
import asyncio
import collections
import io
import threading
# pip install pydub
# pip install gTTS
# need ffmpeg, pyAudio or simpleaudio.
import gtts
import pydub
import pydub.playback
from chzzkpy import Client, Message, UserPermission
# Configuration
client_id = "client_id"
client_secret = "client_secret"
loop =... | Python | 1 |
"generate_hw_factors", generate_hw_factors)
graph.add_node("save_hw_factors", save_hw_factors)
graph.add_node("generate_optimization_hints", generate_optimization_hints)
graph.add_node("save_optimization_hints", save_optimization_hints)
graph.add_node("generate_sketch_kernel", generate_sketch_kernel)
... | Python | 1 |
Cow::Borrowed(path.as_ref())
}
}
// ---
// From impls: owned -> owned
// ---
impl From<Box<Utf8Path>> for Utf8PathBuf {
fn from(path: Box<Utf8Path>) -> Utf8PathBuf {
path.into_path_buf()
}
}
impl From<Utf8PathBuf> for Box<Utf8Path> {
fn from(path: Utf8PathBuf) -> Box<Utf8Path> {
... | Rust | 0 |
<gh_stars>0
use crate::relayer::Relayer;
use ckb_logger::{debug_target, warn_target};
use ckb_network::CKBProtocolContext;
use ckb_types::{core, packed, prelude::*};
use failure::Error as FailureError;
use futures::{self, future::FutureResult, lazy};
use std::sync::Arc;
pub struct BlockProposalProcess<'a> {
messag... | Rust | 0 |
uf=self.bufferList[bufferIndex]
dummySinger.sing( buf, seq, self.tempo, self.refFreq)
return bufferIndex
def trackToWav(self, bufferIndex, filename):
WriteTrackBufferToWav(self.bufferList[bufferIndex], filename)
def mix(self, targetBuf):
MixTrackBufferList(targetBuf,self.buffer... | Python | 1 |
into_iter()
//! .zip(&(*sd))
//! .map(|(x, &y)| (x, vec![y])),
//! complot::complot!(
//! "spectral_density.png",
//! xlabel = "Frequency [Hz]",
//! ylabel = "Spectral density [s^2/Hz]"
//! ),
//! )
//! .into();
//!}
//!```
mod builder;
mod... | Rust | 0 |
from django.test import TestCase
from django.template import Context, Template, TemplateSyntaxError
class IndentByTagExceptions(TestCase):
"""Test for indentby exceptions."""
def test_should_raise_TemplateSyntaxError_if_args_lenght_not_in_2_4(self):
content = """{% load indent_text %}
{% indentby %}
... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2013 Communications Engineering Lab (CEL) / Karlsruhe Institute of Technology (KIT)
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either... | Python | 1 |
")'
)
files.add(path)
return files
def egg2dist(self, egginfo_path, distinfo_path):
"""Convert an .egg-info directory into a .dist-info directory"""
def adios(p):
"""Appropriately delete directory, file or link."""
if os.path... | Python | 1 |
,
'model_state_dict': model.state_dict(),
'val_auc': val_auc
}, output_dir / f"best_overall_auc_{val_auc:.4f}.pt")
logger.info(f"✅ New best AUC: {val_auc:.4f}")
logger.info(f"\n🎉 Training complete! Best AUC: {best_auc:.4f}")
logger.info(f... | Python | 1 |
/ Convenience macro for turning a comma-separated list of values into a value tuple.
#[macro_export]
macro_rules! make_tuple_value {
($($exprs:expr),*) => {
Val::Tuple(Tuple { elems: vec!($($exprs),*) })
}
}
impl Tuple {
/// Creates a tuple with no elements.
pub fn empty() -> Tuple {
Tuple { elems: Vec::new() ... | Rust | 0 |
. 2.. 3..\n".as_bytes();
write(&path, &bytes).expect("`test_append` failed to `hofund::write`");
assert!(append(&path, &bytes).is_ok());
let left = "testing... 1.. 2.. 3..\ntesting... 1.. 2.. 3..\n".as_bytes();
let middle = read(&path).expect("`test_append` failed to `hofund::read`");
... | Rust | 0 |
import cv2 as cv
import numpy as np
def get_contours(img, imgContour):
contours, hierarchy = cv.findContours(img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv.contourArea(cnt)
if area > 500:
cv.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
p... | Python | 1 |
required=True)
parser.add_argument("--guide", type=str, default="n2n")
parser.add_argument("--port", type=int, default=6009)
parser.add_argument("--per_editing_step", type=int, default=50000000)
parser.add_argument("--den_percent", type=float, default=0.0)
parser.add_argument("--coarse_iteration",... | Python | 1 |
def get_regression_estimate(X, neuron_idx):
"""
Estimates the connectivity matrix using lasso regression.
Args:
X (np.ndarray): our simulated system of shape (n_neurons, timesteps)
neuron_idx (int): a neuron index to compute connectivity for
Returns:
V (np.ndarray): estimated connectivity matrix ... | Python | 1 |
self.protocol + "://" + self.ad_server_host + ":" + self.ad_server_port
get_ads_url = ad_server_url + "/ad/user/" + user_id + "/serve?device_type=" + device_type + "&city=" \
+ city + "&state=" + state
print(get_ads_url)
response_json = {}
... | Python | 1 |
}
/// Registers the `on_error` callback.
pub fn on_error<F>(&mut self, function: F) -> Result<(), Error>
where
F: Fn(String) + 'static + Sync + Send + Send,
{
if self.serving.load(Ordering::Relaxed) {
return Err(Error::IllegalActionAfterOpen);
}
self.transp... | Rust | 0 |
部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,杂乱的背景,三条腿,背景人很多,倒着走",
input_image=ref_frame,
num_inference_steps=50,
cfg_scale=1.5, # slow
# cfg_scale=1.0, # fast
seed=seed, tiled=True,
dwpose_data=dwpose_data,
random_ref_dwpose=random_ref_dwpose_tmp,
height=height,
... | Python | 1 |
ife',
'wifi',
'wilderness',
'wildlife',
'will',
'willow',
'win',
'wind',
'windmill',
'window',
'windows',
'windscreen',
'windsurfing',
'wine',
'wing',
'winner',
'winning',
'winter',
'wire',
'wireless',
'wisdom',
'wish',
'witch',
... | Python | 1 |
ger":
metrics_data = [
{"icon": "💰", "value": "$24,589", "label": "Today's Sales", "change": "12.5%", "change_type": "positive"},
{"icon": "👥", "value": "186", "label": "Customers Today", "change": "8.3%", "change_type": "positive"},
{"icon": "📦", "value": "45", "label": "... | Python | 1 |
0923\r\n:16383\r\n*3\r\n$12\r\n192.168.80.6\r\n:6379\r\n$40\r\n3a7c357ed75d2aa01fca1e14ef3735a2b2b8ffac\r\n*3\r\n$12\r\n192.168.80.3\r\n:6379\r\n$40\r\n77c01b0ddd8668fff05e3f6a8aaf5f3ccd454a79\r\n*4\r\n:5461\r\n:10922\r\n*3\r\n$12\r\n192.168.80.5\r\n:6379\r\n$40\r\n969c6215d064e68593d384541ceeb57e9520dbed\r\n*3\r\n$12\... | Rust | 0 |
u32, s: u32, nano: u32) -> Duration {
try_from_hms_nano(h, m, s, nano).unwrap()
}
/// Converts given value to a `String` according to ISO 8601 standard with day
/// as largest unit.
pub fn to_iso8601(duration: &Duration) -> String {
let secs = duration.as_secs_f64();
if secs == 0.0 {
"PT0S".to_st... | Rust | 0 |
}
#[pallet::error]
pub enum Error<T> {
InvalidPonyId,
SameGender,
NoChemistry,
}
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::call]
impl<T:Config> Pallet<T> {
/// Create a new Pony
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.