text string | label_name string | labels int64 |
|---|---|---|
yzed} bytes) in {duration:.1f} seconds "
f"({packets_per_second:.1f} packets/sec)"
)
self.status_callback(True, status_message)
def _get_default_interface(self) -> Optional[str]:
"""Get the default network interface.
Returns:
str: In... | Python | 1 |
from flask import Flask, render_template, Response, request
import cv2
import mediapipe as mp
import numpy as np
from playsound import playsound
import threading
app = Flask(__name__)
# Global variables
camera = cv2.VideoCapture(0)
camera_active = True
min_posture_y = 1
latest_landmarks = None
sound_played = False
#... | Python | 1 |
ng with borrowck.
let handle_result =
|cached_result: &Result<Rc<CachedRuntime>, CacheError>| match *cached_result {
Err(_) => Err(Error::InvalidCode),
Ok(ref cached_runtime) => Ok(Rc::clone(cached_runtime)),
};
match self.instances.entry(code_hash.into()) {
Entry::Occupied(o) => handle_result(o.g... | Rust | 0 |
&password_temp.iter().cloned().collect::<String>(),
log_pos,
) {
break;
}
}
EditorEvent::Exit => break,
}
});
... | Rust | 0 |
The full path of this endpoint.
///
/// Automatically implemented.
fn full_path(&self, is_sandbox: bool) -> String {
if is_sandbox {
format!("{}{}", SANDBOX_ENDPOINT, self.relative_path())
} else {
format!("{}{}", LIVE_ENDPOINT, self.relative_path())
}
}
}... | Rust | 0 |
"""
Allocate and initialize first simplex to begin Amoeba algorithm
"""
optimizer.amoeba.debug = 0 ;
"""Allocate a 5x5 matrix that holds simplex and function results"""
optimizer.amoeba.init_simplex = trick.alloc_type(5, "double *")
optimizer.amoeba.init_simplex[0] = trick.alloc_type(5, "double")
optimizer.amoeba.... | Python | 1 |
...Sargento 1o Aguilar\nIsmael Martinez ....Cabo 1o Carranza\nNasser Saleh ....Alferez Abda\nMariam Hernandez ....Sargento Castro\nRuth Gabriel ....Brigada Alvite\nYounes Bachir ....Soldado Rashid\nDavid de la Torre ....Soldado Vazquez\nJavier Bodalo ....Cabo Angulo\nBerta Hernandez ....Cabo Sobrino\nSergio Momo ....So... | Python | 1 |
, Ord, Hash)]
pub enum ErrorLevel {
Info,
Warning,
Error,
}
/// Contains the full information of an error.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Error {
pub msg: String,
pub src: Source,
pub r#type: ErrorType,
p... | Rust | 0 |
ssertEqual(stay_vc.status, helpers.CandidateStatus.Rejected)
self.assertEqual(soft_vc.status, helpers.CandidateStatus.Rejected)
self.assertEqual(hard_vc.status, helpers.CandidateStatus.Hopeful)
def test_transfere_votes(self):
candidates, _ = self.get_candidates_and_ballots()
stay, s... | Python | 1 |
r_radius": 8, # Радиус скругления углов
"border": ft.border.all(1, ft.Colors.GREY_700), # Тонкая серая граница
}
@staticmethod
def set_window_size(page: ft.Page):
"""
Установка фиксированного размера окна приложения
Args:
page (ft.Page)... | Python | 1 |
allowed.
//!
//!
//! ## Current features
//!
//! This implementation now supports all of the features of the engine.io protocol mentioned [here](https://github.com/socketio/engine.io-protocol).
//! This includes various transport options, the possibility of sending engine.io packets and registering the
//! common engi... | Rust | 0 |
ଦ\u{b4d}ୟ ଉପଯୋଗୀ ତ\u{b43}ଣ",
],
},
#[cfg(feature = "pa")]
crate::Annotation {
lang: "pa",
tts: Some("ਚਾਰ ਪ\u{a71}ਤਿਆ\u{a02} ਵਾਲਾ ਲ\u{a4c}\u{a02}ਗ"),
keywords: &[
"ਚਾਰ",
"ਚਾਰ ਪ\u{a71}ਤਿਆ\u{a02} ਵਾਲਾ ਲ\u{a4c}\u{a02}ਗ",... | Rust | 0 |
from print import print
import requests
SHEET_ENDPOINT = "https://api.sheety.co/1077e6215b2440d7ebcaf3b791bdb55f/flightDeals/prices"
class DataManager:
#This class is responsible for talking to the Google Sheet.
def __init__(self):
self.destination_data = {}
def get_destination_data(self):
... | Python | 1 |
import pandas as pd
msg=pd.read_csv('naivetext.csv',names=['message','label'])
print("the dimension of the dataset",msg.shape)
msg['labelnum']=msg.label.map({'pos':1,'neg':0})
X=msg.message
y=msg.labelnum
print(X)
print(y)
from sklearn.model_selection import train_test_split
Xtrain,Xtest,ytrain,ytest=train_test_spl... | Python | 1 |
GetResults()?).expect("send over mpsc channel");
}
Ok(())
}))?;
wait_with_pump(rx)?;
Ok(self)
}
pub fn dispatch<F>(&self, f: F) -> Result<&Self>
where
F: FnOnce(WebView) + Send + 'static,
{
self.tx.send(Box::new(f)).expect("se... | Rust | 0 |
Pose {
fn eval_pose(
&self,
nodes: &Pool<PoseNode>,
params: &ParameterContainer,
animations: &AnimationContainer,
dt: f32,
) -> Ref<AnimationPose>;
fn pose(&self) -> Ref<AnimationPose>;
}
impl EvaluatePose for PoseNode {
fn eval_pose(
&self,
node... | Rust | 0 |
libc::LOG_LOCAL7 => Ok(Facility::Local7),
libc::LOG_LPR => Ok(Facility::Lpr),
libc::LOG_MAIL => Ok(Facility::Mail),
#[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
libc::LOG_NTP => Ok(Facility::Ntp),
#[cfg(any(target_os = "macos", target_os ... | Rust | 0 |
i_test_dir::*;
//! // Fails.
//! # #[cfg(unix)]
//! let testdir = TestDir::new("true", "true_fails");
//! # #[cfg(windows)]
//! # let testdir = TestDir::new("cmd", "true_fails");
//! let mut cmd = testdir.cmd();
//! # #[cfg(windows)]
//! # cmd.args(&["/C", "exit 0"]);
//! cmd.expect_failure();
//! ```
//!
//! ## File i... | Rust | 0 |
C_INS_MTVSRD = 824,
PPC_INS_MTVSRDD = 825,
PPC_INS_MTVSRWA = 826,
PPC_INS_MTVSRWS = 827,
PPC_INS_MTVSRWZ = 828,
PPC_INS_MTXER = 829,
PPC_INS_MULHD = 830,
PPC_INS_MULHDU = 831,
PPC_INS_MULHW = 832,
PPC_INS_MULHWU = 833,
PPC_INS_MULLD = 834,
PPC_INS_MULLI = 835,
PPC_INS_MUL... | Rust | 0 |
{
Ok(index) => index,
Err(..) => return Ok(false),
};
let var =
match this
.scopes
.try_get_var(ident.as_ref(), this.source_id, this.visitor, path.span())?
{
Some(var) => var,
None => return Ok(false),
};
this.asm.pus... | Rust | 0 |
from .SpecImports import *
from toontown.toonbase import ToontownGlobals
CogParent = 100007
CogParent1 = 100009
BattlePlace1 = 100004
BattlePlace2 = 100005
BattleCellId = 0
BattleCellId1 = 1
BattleCells = {BattleCellId: {'parentEntId': BattlePlace1,
'pos': Point3(0, 0, 0)},
BattleCellId1: {'parentEntId... | Python | 1 |
0000: speed_t = 0o010_013;
pub const B2500000: speed_t = 0o010_014;
pub const B3000000: speed_t = 0o010_015;
pub const B3500000: speed_t = 0o010_016;
pub const B4000000: speed_t = 0o010_017;
pub const CSIZE: tcflag_t = 0o000_060;
pub const CS5: tcflag_t = 0o000_000;
pub const CS6: tcflag_t = 0o000_020;
pub const CS7: ... | Rust | 0 |
self.skip(link)?;
self.spongos.join(&mut s);(self)
}
}
*/
impl<'a, TW, F, L: SkipFallback<TW, F>, S: LinkStore<TW, F, L>, OS: io::OStream<TW>> Join<&'a L, &'a S>
for Context<TW, F, OS>
where
TW: SpongosTbitWord,
F: PRP<TW>,
{
fn join(&mut self, store: &'a S, link: &'a L) -> Fallible... | Rust | 0 |
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
from airbyte_cdk.test.mock_http.response_builder import FieldPath, NestedPath
from .records_builder import ZendeskSupportRecordBuilder
class TicketFormsRecordBuilder(ZendeskSupportRecordBuilder):
@classmethod
def ticket_forms_record(cls) -> "TicketFor... | Python | 1 |
cr(&input).expect("ocr failed");
println!("{}", res);
}
<filename>abin/src/implementation/internal/vec.rs<gh_stars>1-10
use core::{mem, slice};
use crate::spi::{BinData, FnTable, UnsafeBin};
use crate::{Bin, BinFactory, IntoUnSyncView, NewBin, NewSBin, SBin};
/// A binary that is backed by a `Vec<u8>`. Note: It'... | Rust | 0 |
all(&query)?;
let mut res = vec![];
stream.read_to_end(&mut res)?; ... | Rust | 0 |
tops.push(SysResVO::from(&item));
}
}
//find child
for mut item in &mut tops {
self.loop_find_childs(&mut item, all_res);
}
Ok(tops)
}
///死循环找出父-子 关联关系数组
pub fn loop_find_childs(&self, arg: &mut SysResVO, all_res: &BTreeMap<Str... | Rust | 0 |
import os
import shutil
import subprocess
import winreg
# Paths and registry keys
CYLANCE_REGISTRY_KEY = r"folder with(\Cylance\Desktop)"
CYLANCE_SERVICES = ["cylancesvc", "cylanceui", "cyoptics"]
CYLANCE_DRIVERS_PATH = r"C:\Windows\System32\drivers\\"
CYLANCE_DRIVER_FILES = [
"CylanceDrv64.sys",
"CyOpticsDrv.... | Python | 1 |
#
# Copyright (c) 2021-2024 Semgrep Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# version 2.1 as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT AN... | Python | 1 |
>) -> DSBlockMatrix<U<M>, U<M>>
where
N: Array<<M as Array<f64>>::Array> + std::ops::Mul<M>,
M: Copy + Default + Unsigned + Array<f64> + Array<<M as Array<f64>>::Array> + std::ops::Mul<M>,
<M as Mul<M>>::Output: Copy + Default + Unsigned + Array<f64>,
StaticRange<... | Rust | 0 |
mId=numId)
xml = DXB.xml(lis)
return etree.fromstring(xml)
class InvalidIlvlOrderTestCase(_TranslationTestCase):
expected_output = '''
<html>
<ol data-list-type="decimal">
<li>AAA
<ol data-list-type="decimal">
<li>BBB</li>
... | Python | 1 |
"20273": "IBM EBCDIC Germany",
"20277": "IBM EBCDIC Denmark-Norway",
"20278": "IBM EBCDIC Finland-Sweden",
"20280": "IBM EBCDIC Italy",
"20284": "IBM EBCDIC Latin America-Spain",
"20285": "IBM EBCDIC United Kingdom",
"20290": "IBM EBCDIC Japanese Katakana Extended",
"20297": "IBM EBCDIC Fr... | Python | 1 |
ing adds an extra '0' on the left to
avoid a leading thousands separator. For example, inserting
commas every three digits in '123456', with min_width=8, gives
'0,123,456', even though that has length 9.
rD rF r, group length should be positiver> r Nrd r r r r r r reversed)r r min_wi... | Python | 1 |
;
pub type ResultOutput = Result<Vec<Result<eval::Output, eval::Error>>, pom::Error>;
pub fn fmt(
f: &mut impl io::Write,
username: &str,
input: &str,
output: &ResultOutput,
) -> io::Result<()> {
writeln!(
f,
"{} rolled ... {}\nand got ... {}",
username,
input,
... | Rust | 0 |
Client`].
///
/// [`reqwest::Client`]: https://docs.rs/reqwest/0.10.1/reqwest/struct.Client.html
///
/// [`Bot`]: crate::Bot
/// [`reqwest::Proxy::all`]: https://docs.rs/reqwest/latest/reqwest/struct.Proxy.html#method.all
#[must_use]
pub fn build(self) -> Bot {
Bot {
clie... | Rust | 0 |
IS NULL AND step = ? LIMIT ?', (glob.wq_stage,count) )
else:
curs.execute('SELECT cbid FROM todos WHERE next_arg IS NULL AND assigned IS NULL ORDER BY id LIMIT ?', (count,) )
res = curs.fetchall()
cbids = []
for r in res:
cbids.append(r['cbid'])
if len(cbids)>0:
upd_str = ... | Python | 1 |
}
pub fn get_min_value(&self) -> f64 {
unsafe { wb_distance_sensor_get_min_value(self.0) }
}
pub fn get_aperture(&self) -> f64 {
unsafe { wb_distance_sensor_get_aperture(self.0) }
}
pub fn get_lookup_table_size(&self) -> i32 {
unsafe { wb_distance_sensor_get_lookup_tab... | Rust | 0 |
input dimensions.
# TODO (pad to be divided by 4)
self.num_embeddings = num_embeddings
self.org_vocab_size = org_num_embeddings or num_embeddings
# self.num_embeddings_padded = pad_vocab_size(num_embeddings,
# padding_size)
self.embedding_dim = embedd... | Python | 1 |
raise
except Exception as e:
# 添加详细的错误日志记录
import traceback
import logging
logger = logging.getLogger(__name__)
logger.error(f"登录过程中发生异常: {str(e)}")
logger.error(f"异常堆栈: {traceback.format_exc()}")
raise HTTPException(
status_code=status.HTTP_500_... | Python | 1 |
let gNodeMid = if intp.rgatemod == 3 {
let name = format!("{}.{}", path, "midgate");
Some(vars.add(name, VarKind::V))
} else {
gNodeExt
};
/* internal body nodes for body resistance model */
let (dbNode, bNodePrime, sbNode) = if intp.rbodymod... | Rust | 0 |
n's ID."]
#[doc = ""]
#[doc = " This returns the identifier associated with this transaction. For a"]
#[doc = " read-only transaction, this corresponds to the snapshot being read;"]
#[doc = " concurrent readers will frequently have the same transaction ID."]
#[doc = ""]
#[doc = " @param[in] txn ... | Rust | 0 |
))
for l, layer in enumerate(self.layers):
y = th.zeros(g.number_of_nodes(), self.n_hidden if l != len(self.layers) - 1 else self.n_classes)
for start in tqdm.trange(0, len(nodes), batch_size):
end = start + batch_size
batch_nodes = nodes[start:end]
... | Python | 1 |
TetraError::InvalidFont)?,
base: base.ok_or(TetraError::InvalidFont)?,
pages,
glyphs,
kerning,
})
}
}
impl Rasterizer for BmFontRasterizer {
fn rasterize(&self, glyph: char, _: Vec2<f32>) -> Option<RasterizedGlyph> {
if let Some(bmglyph) = self.gl... | Rust | 0 |
len > MAX_CID_SIZE + 1 {
return Err(invalid_data(MessageTooLarge(msg_len)));
}
self.buffer.resize(msg_len, 0);
io.read_exact(&mut self.buffer).await?;
let request = BitswapRequest::from_bytes(&self.buffer).map_err(invalid_data)?;
Ok(request)
}
async fn read_r... | Rust | 0 |
-allocations quickly
// include a buffer (20 bytes)
let n = it.size_hint().0 + 2;
let guess =
(cmp::max(s1.len(), s2.len()) * n) + (this.len() * (n - 1)) + 20;
let mut r = Stri... | Rust | 0 |
id = 1 or id = 2) and a like 'abc'", "(s.id = 1 or s.id = 2) and json_extract(data, '$.a') like 'abc'"
)
self.assertSql(
"where",
prefix + "where a > f(d(b, c, 1),1)",
"json_extract(data, '$.a') > f(d(json_extract(data, '$.b'), json_extract(data, '$.c'), 1), 1)",
... | Python | 1 |
}
/// The `filter()` routine, if used, must be called before `initscr()` is
/// called. The effect is that, during those calls, `LINES` is set to 1;
/// the capabilities clear, cup, cud, cud1, cuu1, cuu, vpa are disabled;
/// and the home string is set to the value of cr. The effect is that the
/// cursor is confined... | Rust | 0 |
"""
Problem: Longest Common Prefix using Sorting
Description:
------------
Given an array of strings, the task is to find the longest common prefix (LCP) among them.
If there is no common prefix, return an empty string `""`.
Approach:
---------
1. Sort the list of strings lexicographically.
2. After sorting, the firs... | Python | 1 |
"""
任务详情
给定榜单中任意视频号名称,完成以下任务
任务要求
1. 函数接收 str 数据类型的微信视频号名称 videoname;
2. 函数返回为 list 数据类型;
3. 输出 list 中包含 预估粉丝数,日作品数,平均点赞,平均转发,平均转发,平均收藏,有望指数
4. 其中 预估粉丝数 要求将“w+”去掉,并将原数乘10000,输出为 int 数据类型
5. 平均转发 要求将“w+”、“w”去掉,并将带“w”的数据乘10000,注意不带“w”的数据不要乘,输出为 int 数据类型
6. 其他数据保持网页原样,输出为 str 数据类型
输出示例 输入 "央视新闻"
[16610000, '211个', '2.0... | Python | 1 |
import random
X = [[2,3],[1,5],[2,8],[7,8],[8,8]]
y = [-1,-1,-1,1,1]
w, b, lr, epochs = [0,0], 0, 0.001, 1000
for _ in range(epochs):
for xi, yi in zip(X,y):
condition = yi*(w[0]*xi[0] + w[1]*xi[1] + b) >= 1
if condition:
w = [w[j] - lr*(2*0.01*w[j]) for j in range(2)]
else:
... | Python | 1 |
from usgs_m2m_connector import USGSM2MConnector | Python | 1 |
pub type objc_id = *mut Object;
macro_rules! DeclareObjcClass
{
(class $t: ident : $p: ident { $($content: tt)* }) =>
{{
let parent = Class::get(stringify!($p)).expect(concat!("objc class ", stringify!($p), "not found"));
let mut d = ClassDecl::new(stringify!($t), parent).expect(concat!("Beginn... | Rust | 0 |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import os
"""
These object can be used throughout project.
1.) Objects from this file can be included in many blueprints
2.) Isolating these object definitions avoids duplication and circular dependencies
"""
# Setup of ... | Python | 1 |
if descriptor_id >= 64 {
return ProgramDescriptor::UserPrivate;
}
if descriptor_id >= 57 {
return ProgramDescriptor::Reserved;
}
unimplemented!();
}
}
}
use std::io::Write;
use crate::error::Result;
use super::super::CompressedBlock;
use super::{util::zigzag_encode, SYNC... | Rust | 0 |
_bbox, p=1)
# Compute the giou cost betwen boxes
cost_giou = -generalized_box_iou(box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox))
if "pred_coords" in outputs:
out_pts = outputs["pred_coords"].flatten(0, 1) # [batch_size * num_queries, 128, 2]
tgt_pts = torch... | Python | 1 |
"""Initial migration
Revision ID: 5c04ace8dbfe
Revises:
Create Date: 2024-09-28 06:47:46.732949
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '5c04ace8dbfe'
down_revision: Union[str, None] = None
branch_labels: Union[... | Python | 1 |
):
"""Generate random positions for 3 obstacles.
Used only for simulated Robot Server.
"""
x_0 = self.np_random.uniform(low=-2.4, high=-1.5)
y_0 = self.np_random.uniform(low=-1.0, high=1.0)
yaw_0 = self.np_random.uniform(low=-np.pi, high=np.pi)
x_1 = self.... | Python | 1 |
Error::Unimplemented,
0x7 => AbiInternalError::Type,
0x8 => AbiInternalError::NotAllowedOperation,
_ => panic!("Invalid error value: `{}`", value),
}
}
}
impl From<AbiInternalError> for i64 {
fn from(value: AbiInternalError) -> Self {
match value {
... | Rust | 0 |
fn pmc_powergate_partition(partition_id: u32, enabled: bool) -> Result<(), ()> {
let pmc_powergate_toggle: &ReadWrite<u32> = &*(0x7000E430 as *mut ReadWrite<u32>);
let pmc_powergate_status: &ReadOnly<u32> = &*(0x7000E438 as *mut ReadOnly<u32>);
let partition_mask = 1 << partition_id;
let state_changed ... | Rust | 0 |
collection: Content::Array(ArrayContent {
length: Box::new(Content::Number(NumberContent::U64(U64::Range(RangeStep {
low: 1,
high: 2,
step: 1,
})))),
content: Box::new(Content::Object(collection)),
}... | Rust | 0 |
e:?})")]
RenderFnFailed {
// This is something like `build_state`
fn_name: String,
template_name: String,
cause: ErrorCause,
// This will be triggered by the user's custom render functions, which should be able to have any error type
#[source]
source: Box<dyn ... | Rust | 0 |
let cpu = Cpu::default();
let code = vec![
0x21, 0x55, 0xAA, // LD HL, $AA55
0x3E, 12, // LD A, 12
0x06, 17, // LD B, 17
0x80, // ADD A,B
0x77, // LD (HL), A
0x3E, 0xFF, // LD A, $FF
0x06, 1, // LD B, 1
0x80, // ADD A,B
0x77, // LD (H... | Rust | 0 |
lue that is not fully known.
/// For example, we may know that it is a number between 1 and 10, but not
/// which particular number.
///
/// When we do know everything about a value, it is concrete rather than
/// abstract, but is convenient to just use this structure for concrete values
/// as well, since all operatio... | Rust | 0 |
QMessageBox QLabel {
color: #2c3e50;
}
""")
msg.exec()
def _show_success(self, message):
"""Mostra mensagem de sucesso"""
msg = QMessageBox()
msg.setIcon(QMessageBox.Icon.Information)
msg.setWindowTitle("Sucesso")
msg.setT... | Python | 1 |
InterruptRequest => self.interrupt.set_request(value),
BootromUnmap => self.is_booting = value != 1,
HighRam(offset) => {
//println!("high ram: {} <- {}", offset, value);
self.high_ram[offset as usize] = value
}
... | Rust | 0 |
::default();
if !before.is_empty() {
query_args.push(("before".to_string(), before.to_string()));
}
if !count.is_empty() {
query_args.push(("count".to_string(), count.to_string()));
}
if !page.is_empty() {
query_args.push(("page".to_string(), p... | Rust | 0 |
78, 97, 109, 101, 120, 29, 68, 105, 115, 112, 108, 97, 121, 101, 100, 32, 67, 97, 108, 108, 97, 32, 86, 105, 114, 103, 105, 110, 105, 101, 32, 68, 97, 110, 97, 4, 129, 162, 99, 97, 108, 103, 38, 100, 116, 121, 112, 101, 106, 112, 117, 98, 108, 105, 99, 45, 107, 101, 121];
// use serde::de;
// let mut d... | Rust | 0 |
i32 {
return 4 * tree_size(depth) / tree_size(i);
}
fn populate(mut depth: i32, this_node: Gc<Node>) {
if depth <= 0 {
return;
} else {
depth -= 1;
this_node.get_mut().left = Some(Gc::new(Node::leaf()));
this_node.get_mut().right = Some(Gc::new(Node::leaf()));
popul... | Rust | 0 |
sg failed.")?;
tracing_log::LogTracer::init().with_context(|| {
"Failed to init LogTracer with terminal logger and kmsg logger."
})?;
Ok(())
};
inner()
.with_context(|| "Failed to init the logger")
.unwrap();
}
}
pub fn in... | Rust | 0 |
class Solution:
def canPartition(self, nums):
total = sum(nums)
if total % 2 != 0:
return False
target = total // 2
possible_sums = set([0])
for num in nums:
next_sums = set()
for s in possible_sums:
if s +... | Python | 1 |
import torch as th
from guided_diffusion.image_datasets import load_data
from guided_diffusion import dist_util, logger
import torchvision as tv
import os
import cv2
import random
def get_edges(t):
edge = th.ByteTensor(t.size()).zero_()
edge[:, :, :, 1:] = edge[:, :, :, 1:] | (t[:, :, :, 1:] != t[:, :, :, :-1... | Python | 1 |
Mul),
9 => Ok(Opcode::Div),
10 => Ok(Opcode::Not),
11 => Ok(Opcode::Equal),
12 => Ok(Opcode::Greater),
13 => Ok(Opcode::Less),
14 => Ok(Opcode::Print),
15 => Ok(Opcode::Pop),
16 => Ok(Opcode::DefineGlobal),
17 =>... | Rust | 0 |
# ***************************************************************************
# * Copyright (c) 2019 Werner Mayer <wmayer[at]users.sourceforge.net> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it... | Python | 1 |
}
}
Err(_) => panic!("Failed to decode JSON. Try lowering concurrent connections! Item ID: {} ", ids),
}
}
E... | Rust | 0 |
after an event is pulled out with `epoll_wait()` the associated file descriptor is internally disabled and no other events will be reported by the epoll interface.
///
/// The user must call `epoll_ctl()` with `EPOLL_CTL_MOD` to rearm the file descriptor with a new event mask.
///
/// Valid since Linux 2.6.2.
/// Vali... | Rust | 0 |
distro_response2 = get_container_distribution(gc, "alpine2")
assert distro_response1["results"][0]["base_path"] == 'alpine1'
assert distro_response2["results"][0]["base_path"] == 'alpine2'
# Grab the repository href from the json and make get request
repo_response_1 = gc.get(distro_response1["results... | Python | 1 |
"Reader of field `TX_RPTR`"]
pub type TX_RPTR_R = crate::R<u8, u8>;
#[doc = "Transmit FIFO Byte Count\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TX_CNT_A {
#[doc = "0: FIFO is emtpy"]
TX_CNT_0,
}
impl From<TX_CNT_A> for u8 {
#[inline(always)]
fn from(variant: TX_CNT_A) -> Self {
... | Rust | 0 |
from typing import Optional
import torch
import numpy as np
from torchvision.transforms.functional import rgb_to_grayscale
from scipy.stats import entropy
from pnpxai.core._types import Model
from pnpxai.explainers.base import Explainer
from pnpxai.evaluator.metrics.base import Metric
class Complexity(Metric):
... | Python | 1 |
_modes(SymmetricAlgorithmId::Rc2, 4, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 5, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 6, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 7, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 8, 8);... | Rust | 0 |
.clone()
.into_iter()
.dropping(rx_len)
.collect();
(reagent_input, product_input)
}
pub fn substance_list(&self) -> Result<Vec<Sample>, String> {
ReactionList::mass_pairs_to_substances(self.substances.clone())
}
fn str_to_reactant(
for... | Rust | 0 |
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::prelude::{TimeZone, Utc};
use std::borrow::Cow;
#[test]
fn test_dataset_creation_same_day() {
let mut dataset = CalendarDataset::new();
let start = match Utc.datetime_from_str("2020/10/05 12:11:10", "%Y/%m/%d %H:%... | Rust | 0 |
tr]>,
T: AsRef<[&'a str]>,
{
let num_inputs = inputs.as_ref().len();
let (input_tensor, mask) =
self.prepare_for_model(inputs.as_ref(), labels.as_ref(), template, max_length);
let output = no_grad(|| {
let output = self.zero_shot_classifier.forward_t(
... | Rust | 0 |
Box::new(lift_expr(ctx, right)),
),
TKind::App(_, _) => todo!(),
TKind::TupleField(tuple, idx) => LKind::TupleField(Box::new(lift_expr(ctx, tuple)), *idx),
TKind::If(cond, true_br, false_br) => LKind::If(
Box::new(lift_expr(ctx, cond)),
lift_block(ctx, true_br),
... | Rust | 0 |
w Pertama
def landing_page():
for widget in root.winfo_children():
widget.destroy()
header_label = tk.Label(root, text="Monitor 10 \nToll Gate System", font=("Arial", 24), fg="white", bg="#3386FF", )
header_label.pack(pady=10, padx=10)
header_label = tk.Label(root, text="Pengenalan Komputasi -... | Python | 1 |
def test_stable_diffusion_xl_save_from_pretrained(self):
pipes = []
components = self.get_dummy_components()
sd_pipe = StableDiffusionXLPipeline(**components).to(torch_device)
pipes.append(sd_pipe)
with tempfile.TemporaryDirectory() as tmpdirname:
sd_pipe.save_pretrained(tmpdirname)
... | Python | 1 |
olve_unit_norm_primal(lhs, rhs, d_hat0, step_size=0.1, max_iter=1000,
factr=1e11, verbose=0):
"""Solve d_hat in the primal using projected gradient descent.
Stop when (f^k - f^{k+1})/max({|f^k|,|f^{k+1}|,1}) <= factr * eps
where eps is machine precision.
"""
def func(d_h... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Created on Sat May 17 22:08:40 2025
@author: jwang
"""
def convertToBinary(n):
binary_result = ""
while(n > 0):
binary_result = str(n % 2) + binary_result
n = n // 2
return binary_result
def findComplement(num):
"""
:type num: int
:rtype: int
... | Python | 1 |
arg_params['fpn_p4_1x1_weight'] = mx.random.normal(0, 0.01, shape=self.arg_shape_dict['fpn_p4_1x1_weight'])
arg_params['fpn_p4_1x1_bias'] = mx.nd.zeros(shape=self.arg_shape_dict['fpn_p4_1x1_bias'])
arg_params['fpn_p3_1x1_weight'] = mx.random.normal(0, 0.01, shape=self.arg_shape_dict['fpn_p3_1x1_weight... | Python | 1 |
from eth2spec.test.context import (
spec_test,
with_config_overrides,
with_matching_spec_config,
with_phases,
with_presets,
with_state,
)
from eth2spec.test.helpers.constants import (
BELLATRIX,
CAPELLA,
DENEB,
MINIMAL,
)
from eth2spec.test.helpers.light_client_data_collection im... | Python | 1 |
ableSerialBase.seekable! r c U R [ U5 5 n[ U5 n X!S U& |