text string | label_name string | labels int64 |
|---|---|---|
layers: self.layers,
activation: self.activation,
input_size: self.input_size
}
}
}<gh_stars>1-10
use core::ops::Range;
use rand::Rng;
use serde::{Deserialize, Serialize};
/// A stat amount for a Pokemon.
/// Used in a Pokemon's IVs and EVs.
pub type Stat = u8;
/// BaseStats are [... | Rust | 0 |
.inner.seek(SeekFrom::Current(4))?;
self.inner.write_u64::<LittleEndian>(self.form_length)?;
self.is_rf64 = true;
}
Ok(())
}
/// Add `amount` to the RIFF/RF64 form length
fn increment_form_length(&mut self, amount: u64) -> Result<(), std::io::Error> {
self.fo... | Rust | 0 |
u32 = 50;
pub const EM_X86_64: u32 = 62;
pub const EM_S390: u32 = 22;
pub const EM_CRIS: u32 = 76;
pub const EM_M32R: u32 = 88;
pub const EM_MN10300: u32 = 89;
pub const EM_OPENRISC: u32 = 92;
pub const EM_BLACKFIN: u32 = 106;
pub const EM_ALTERA_NIOS2: u32 = 113;
pub const EM_TI_C6000: u32 = 140;
pub const EM_AARCH64:... | Rust | 0 |
et mut weights3d = Vec::with_capacity(n * n * n);
let mut points3d = Vec::with_capacity(n * n * n);
let rule1d_iter = || weights1d.iter().zip(&points1d);
for (&wx, &[x]) in rule1d_iter() {
for (&wy, &[y]) in rule1d_iter() {
for (&wz, &[z]) in rule1d_iter() {
let w = wx ... | Rust | 0 |
#[cfg(unix)]
fn ret_code_from_exit_status(status: ExitStatus) -> i32 {
status
.code()
.or_else(|| status.signal().map(|x| -x))
.unwrap_or(1)
}
/// Command evaluation environment in a Docker container.
///
/// Attention:
/// - Every `DockerCommandRunner` instance includes a `DropBomb`,
/// ... | Rust | 0 |
(t.plus_seconds(delta)))
}
(Scheduled::AtHeight(h), Duration::Height(delta)) => Ok(Scheduled::AtHeight(h + delta)),
_ => Err(StdError::generic_err("Cannot add height and time")),
}
}
}
impl PartialOrd for Scheduled {
fn partial_cmp(&self, other: &Scheduled) -> Option... | Rust | 0 |
valor_prod = float(input('Insira o valor do produto: '))
while True:
print('''1 - Cliente Comum \n2 - Funcionário \n3 - VIP''')
categoria = int(input('Insira sua categoria: '))
match categoria:
case 1:
print(f'O valor do seu produto é de: R${valor_prod}')
break
case... | Python | 1 |
ted and numbered wavs.
# Basically a reference table.
# If sample library is organized, by drum machine for example, this text file is useful for looking up the instrument or drum name of samples.
with open(os.path.join(outdir, "original_filenames.txt"), "w") as output:
for orig_wav in list_of_dir_w... | Python | 1 |
,
65, 84, 44, 50, 10, 71, 71, 84, 67, 65, 44, 50, 10, 71, 71, 84, 67, 71, 44, 50, 10, 71, 71,
84, 84, 65, 44, 50, 10, 71, 71, 84, 84, 71, 44, 50, 10, 71, 71, 84, 71, 67, 44, 50, 10, 71,
71, 84, 71, 84, 44, 50, 10, 71, 71, 71, 65, 65, 44, 50, 10, 71, 71, 71, 65, 71, 44, 50, 10,
71, 71, 71... | Rust | 0 |
_map_update_elem(fd, key, val, flags) };
check_rc(rc, (), "Error updating elem")
}
pub(crate) fn lookup_elem(fd: i32, key: *const c_void, val: *mut c_void) -> i32 {
unsafe { bpf::bpf_map_lookup_elem(fd, key, val) }
}
pub(crate) fn update_batch(
fd: i32,
key: *mut c_void,
val: *mut c_void,
coun... | Rust | 0 |
"""
Classifies: CHEBI:23053 catechin
"""
"""
Classifies: Catechin class – Members of the class of hydroxyflavan that have a flavan-3-ol skeleton and its substituted derivatives.
"""
from rdkit import Chem
def is_catechin(smiles: str):
"""
Determines if a molecule belongs to the catechin class based on its SMI... | Python | 1 |
onents.get('combos', 0) > 0:
print("\n[9] Setting division in iframe...")
combo_result = await frame.evaluate("""
() => {
const combos = Ext.ComponentQuery.query('combobox');
... | Python | 1 |
_bytes * 2..(i + 1) * sew_bytes * 2
}
_ => range.clone(),
};
let lhs_range = match cat {
WideningCategory::VdVs2 => i * sew_bytes * 2..(i + 1) * sew_bytes * 2,
WideningCategory::Vs2Only => i * sew_bytes * 2..(i + 1) * sew_bytes * 2,
WideningCat... | Rust | 0 |
, c) = (b OR NOT(c)) XOR a (64 <= j <= 79)
// Note: It's the same as the third round function but with permuted variables
round_idx if (64..=79).contains(&round_idx) => (
|a, b, c| (b | (!c)) ^ a,
|cs, i, a, b, c| {
let t = Boolean::or(cs.ns(|| format!("B OR NOT C... | Rust | 0 |
iloc[-recent_data:].values.reshape(-1, 1)
y = price1.iloc[-recent_data:].values
reg = LinearRegression().fit(X, y)
hedge_ratio = reg.coef_[0]
return hedge_ratio
except Exception as e:
logger.warning(f"對沖比率計算失敗: {e... | Python | 1 |
<Self::Dimension as dimensions::Dimension>::Cell,
) {
let cell_index: usize = cell.into();
let num_bytes = bits.size();
let start_bit = (num_bytes * 8) - (level + 1) * Self::DIMENSIONALITY;
let end_bit = start_bit + Self::DIMENSIONALITY;
bits.set_bits_from_usize(start_bit..e... | Rust | 0 |
ND: mul-chip-trait-impl
// ANCHOR: mul-chip-impl
impl<F: FieldExt> MulChip<F> {
fn construct(config: <Self as Chip<F>>::Config, _loaded: <Self as Chip<F>>::Loaded) -> Self {
Self {
config,
_marker: PhantomData,
}
}
fn configure(
meta: &mut ConstraintSystem<F... | Rust | 0 |
value
});
}
macro_rules! jvmti_call_ptr_result {
( $jvmtienv:expr, $type:tt, $name:tt $(, $args:expr )* ) => ({
let mut value: $type = ptr::null_mut();
let res = jvmti_call_result!($jvmtienv, $name,
$($args),*,
&mut value
);
jvmti_error_code_to_res... | Rust | 0 |
# AIDEV-NOTE: Workflow name parsing utility for extracting base workflow from transition strings.
from ...autogen.openapi_model import Transition
PAR_PREFIX = "PAR:"
SEPARATOR = "`"
def get_workflow_name(transition: Transition) -> str:
workflow_str = transition.current.workflow
if workflow_str.startswith(PAR... | Python | 1 |
import matplotlib.pyplot as plt
loss_non_linear = None # loss value in training log located in checkpoint folder
loss_linear = None # loss value in training log located in checkpoint folder
loss_random = None # loss value in training log located in checkpoint folder
iter_list = [0, 1, 2, 3, 4]
plt.rcParams.update({'fo... | Python | 1 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import os
import posixpath
import shutil
import tempfile
from mozdevice.devicemanager import DMError
from dmunit import... | Python | 1 |
path",
}
define_msg! { pub IndexedTypeIsBothTableOrStr<'a> { indexed: Slot<'a> }:
"ko" => "인덱싱이 되는 `{indexed}` 타입이 테이블인지 문자열인지가 불분명합니다",
_ => "`{indexed}` type that is being indexed should be \
either a table or a string but not both",
}
define_msg! { pub UndefinedStringMeta:
"ko" => "`st... | Rust | 0 |
tick_down_success() {
let mut under_test: Timer = Timer { clock: 5 };
under_test.tick_down();
assert!(under_test.get_value() == 4);
}
#[test]
fn tick_down_no_tick_at_zero() {
let mut under_test: Timer = Timer { clock: 0 };
under_test.tick_down();
assert!(und... | Rust | 0 |
# coding: utf-8
"""
NHL API
Documenting the publicly accessible portions of the NHL API.
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
import datetime
from openapi_cl... | Python | 1 |
= "Bit 5 - Status Register Lock"]
#[inline(always)]
pub fn srl(&self) -> SRL_R {
SRL_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Lock Register Lock"]
#[inline(always)]
pub fn lrl(&self) -> LRL_R {
LRL_R::new(((self.bits >> 6) & 0x01) != 0)
}
}
impl W {
#[do... | Rust | 0 |
efault widget
constructors for the nodes & leaves (BoxWidget
and OvalWidget). The bottom-left tree is
built from tree_to_treesegment."""
twidget = TextWidget(cf.canvas(), text.strip())
textbox = BoxWidget(cf.canvas(), twidget, fill='white', draggable=1)
cf.add_widget(textbox, tc3.bbox()[2]+10, tc2.bbox()[3... | Python | 1 |
test_dataset[test_y.name] = test_y
model = pf.ARIMAX(data=train_dataset,formula=formula,ar=ar,ma=ma)
x = model.fit()
#x.summary()
model_pred = model.predict(h=len(train_y.index)-max(ar, ma), oos_data=train_dataset)
values = np.empty((len(model_pred) + max(ar, ma),1))
... | Python | 1 |
Some(auto_generated_garbling_wire)
}
Role::Evaluator => None,
}
// If called by the evaluator
}
}};
($a:ident <- party $b:expr) => {{
{
// If called by the garbler
$c
// If called by the ... | Rust | 0 |
RefusedNotAuthorized,
}
impl TryFrom<u8> for ReturnCode {
type Error = ();
fn try_from(from: u8) -> Result<ReturnCode, ()> {
Ok(match from {
0 => ReturnCode::Accepted,
1 => ReturnCode::RefusedProtocolVersion,
2 => ReturnCode::RefusedClientIdentifier,
3 ... | Rust | 0 |
handles.push(std::thread::spawn(move || loop {
let index = {
let mut cursor_guard = cursor.lock().unwrap();
let index = *cursor_guard;
if index >= story_ids.len() {
return;
... | Rust | 0 |
0.9061798459386639927976,
];
let w_should = [
0.2369268850561890875143,
0.4786286704993664680413,
0.5688888888888888888889,
0.4786286704993664680413,
0.2369268850561890875143,
];
for (i, x_val) in x_should.iter().en... | Rust | 0 |
from sqlalchemy import Column, Integer, LargeBinary, ForeignKey, DateTime, String
from sqlalchemy.orm import relationship
from datetime import datetime
from .base import Base
class BiometricData(Base):
__tablename__ = 'biometric_data'
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Int... | Python | 1 |
0)?.contains(Interval::new(6, 11)?);
assert!(!check2);
let check3 = Interval::new(5, 10)?.contains(Interval::new(4, 11)?);
assert!(!check3);
Ok(())
}
}
use bevy::prelude::*;
#[derive(Component, Default)]
struct Enemy {
hit_points: u32,
}
fn despawn_dead_enemies(mut commands: ... | Rust | 0 |
= 32);
}
#[test]
fn should_error_if_hex_key_too_long() {
let expected_error = "✘ Key length invalid!".to_string();
let mut long_hex_string = get_example_priv_sk();
long_hex_string.push('a');
long_hex_string.push('b');
match convert_hex_string_to_32_byte_array(long_he... | Rust | 0 |
es
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, "PyDM", "PyDM Documentation", author, "PyDM", "One line description of project.", "Miscellaneous"),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# I... | Python | 1 |
from pathlib import Path
from typing import List, Tuple
from langchain import PromptTemplate, LLMChain
from langchain.document_loaders import TextLoader
from langchain.embeddings import LlamaCppEmbeddings
from langchain.llms import GPT4All
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langcha... | Python | 1 |
.inner.categorize().span_display(), message = %self.inner)
}
}
self
}
}
fn rcxt_display(cxt: &RecordContext) -> &str {
match cxt {
RecordContext::Start => "Start",
RecordContext::End => "End",
RecordContext::Stdout => "Stdout",
RecordContext::Stderr =... | Rust | 0 |
cfg(feature = "tls")]
use tokio_native_tls::TlsConnector;
#[cfg(feature = "rustls-base")]
use tokio_rustls::TlsConnector;
use headers::{Authorization, authorization::Credentials, HeaderMapExt, ProxyAuthorization};
#[cfg(feature = "rustls-base")]
use webpki::DNSNameRef;
type BoxError = Box<dyn std::error::Error + Send ... | Rust | 0 |
.await
.context("build and execute request")?;
if rsp.status() != 200 {
bail!("bad status code: {}", rsp.status());
}
let rsp: SearchResponse = rsp.json().await.context("json deserialize")?;
if rsp.tracks.items.is_empty() {
bail!("found zero tracks");
}
Ok(rsp.tracks.i... | Rust | 0 |
manual fetches fail, this is the interval at which we
// retry.
//
// 30s may seem low, but the default is 5m. More frequent metadata refresh
// rates are surprising to Kafka users, as topic partition counts hardly
// ever change in production.
kafka_config.set("topic.metadata.refresh.interval.... | Rust | 0 |
VecDeque::new(),
mean: 0,
variance: 0,
sent_ping_map: HashMap::new(),
sent_ping_list: VecDeque::new(),
ping_spacing: Duration::from_millis(100),
used_ping_spacing: true,
last_ping_sent: None,
scheduled_send: true,
... | Rust | 0 |
rint(pred_names)
# check that I have the same number of files
assert (len(label_names) == len(pred_names))
print("Evaluating sequences: ", end="", flush=True)
# open each file, get the tensor, and make the iou comparison
complete = len(label_names)
count = 0
percent = 10
#lists for ... | Python | 1 |
::ParametersRejected => Self::ScoFailed,
}
}
}
<reponame>devnought/advent-of-code-2021<filename>day02-pt1/src/main.rs
use std::{error::Error, fmt};
use common::read_input;
use nom::{
branch::alt,
bytes::complete::tag,
character::complete::{digit1, space1},
combinator::map_res,
sequence:... | Rust | 0 |
racter>>,
mut character_state: ResMut<State<CharacterState>>,
mut health_changed_event_writer: EventWriter<HealthChangedEvent>,
) {
let (mut health, transform, mut damage_cooldown) = query.single_mut();
let mut damage_applied = false;
if transform.translation.x > DAMAGE_TRESHOLD_X_POSITION && dama... | Rust | 0 |
"""
Write a python function that takes in an integer n and returns the sum of the squares of the first n odd natural numbers.
assert square_Sum(2) == 10
"""
def square_Sum(n):
sum = 0
for i in range(1, n+1):
sum += i**2
return sum
print(square_Sum(2))
/python/python_basics/02_variables/01_variable... | Python | 1 |
= [1 if np.argmax(y[i]) == 1 else 0 for i in range(len(y))]
tpfn += [1 if label[i] == 1 else 0 for i in range(len(y))]
# logger.info('epoch {:d} training loss {:.4f} test loss {:.4f} train acc {:.4f} test acc {:.4f}'
# .format(epoch + 1, np.mean(train_loss), np.mean(test_loss), np.mean(train_ac... | Python | 1 |
st)]
mod tests {}
<filename>algorithms/quicksort/src/lib.rs
trait Partition {
fn do_part(&self, v: &mut Vec<u128>, start: usize, stop: usize, asc: bool) -> usize;
fn do_stack(
&self,
stack: &mut Vec<(usize, usize)>,
ss: (usize, usize),
pivot_comparison_index: usize,
);
}
fn ... | Rust | 0 |
e=85.0,
stars_count=100,
total_issues_count=20,
total_pull_requests_count=8,
total_releases_count=10,
unanswered_issues_count=2,
unassigned_issues_count=5,
)
generate_latest_metrics_pdf(metrics)
mock_bytes_io.assert_called_o... | Python | 1 |
y = 1
if (
# 1
x # 2
:= # 3
y # 4
):
pass
if (
# 1
x # 2
:= # 3
(y) # 4
):
pass
if (
# 1
x # 2
:= # 3
(y) # 4
# 5
):
pass
if (
# 1
x # 2
# 2.5
:= # 3
# 3.5
y # 4
):
pass
if (
# 1
x # 2
# 2.5
:= # 3
# 3.5... | Python | 1 |
import os
import time
from typing import List
from fastapi import APIRouter, UploadFile, HTTPException, status
from app.api.deps import SessionDep, CurrentSuperuserDep
from app.file_storage import default_file_storage
from app.utils.uuid6 import uuid7
from app.models import Upload
from app.types import MimeTypes
from ... | Python | 1 |
m_f32(-1.0).into()];
assert_eq![i32::MIN, Inorm32::from_f32(-1.0).into()];
assert_eq![i64::MIN, Inorm64::from_f32(-1.0).into()];
assert_eq![i128::MIN, Inorm128::from_f32(-1.0).into()];
}
use std::fs::remove_file;
use std::path::Path;
use chrono_tz::America::New_York;
use futures::future::join_all;
use toki... | Rust | 0 |
compare.
keys: The key path being compared.
Raises:
AssertionError: If there are differences in lengths or elements.
"""
if len(a) != len(b):
path = '.'.join(keys)
raise AssertionError(
f'Difference in length at {path}: {len(a)} != {len(b)}'
)
for in... | Python | 1 |
import Moudle
import torch.nn as nn
import torch
from tqdm import tqdm
from torch.utils.data import DataLoader
from WER import WerScore
import os
import DataProcessMoudle
import DecodeMoudle
import videoAugmentation
import numpy as np
import decode
from torch.cuda.amp import autocast as autocast
from torch.cuda.amp imp... | Python | 1 |
ranges=ranges,
termination_symbol=self.blank,
boundary=boundary,
reduction="sum",
delay_penalty=delay_penalty,
)
simple_loss_scale = 0.5
if steps < self.warmup_steps:
simple_los... | Python | 1 |
),
'-v|--verbose Causes the program to produce more output. Specifying it\n multiple times raises the volume of output.'
)
_test_pipeline(
(
(
"-v|--verbose",
10,
10,
),
(
"Cause... | Python | 1 |
class MarzbanError(Exception):
"""Base exception for all Marzban errors"""
code: int
def __str__(self) -> str:
return str(self.code)
def __repr__(self) -> str:
return f"{type(self).__name__}('{self}')"
class DetailedMarzbanError(MarzbanError):
"""Base exception for all Marzban e... | Python | 1 |
name not in ['iSDA', 'iNaturalist']
and 'LANDFIRE' not in node.id
and 'DLR/WSF' not in node.id
):
# Restrict the validnames to start with capital letter.
# Then letters, numbers, and a few more characters
if not re.fullmatch(r'[A-Z][-_ \'.,:a-zA-... | Python | 1 |
ext_summary}\n\nCurrent question: {query}"
logger.info(f"AGENT_QUERY: Enhanced query length: {len(enhanced_query)} characters")
try:
response, new_session_id = self.bedrock_agent.invoke_agent(enhanced_query, privilege, None)
logger.info(f"AGENT_QUERY: Context-enha... | Python | 1 |
ANDER_FEATURE_ID, FeatureAccessLevel.READ_ONLY))])
async def list_functions(
catalog_name: str,
schema_name: str,
catalog_manager: CatalogCommanderManager = Depends(get_catalog_manager)
):
"""List all functions in a schema."""
try:
logger.info(f"Fetching functions for schema: {catalog_name}.... | Python | 1 |
import random
import numpy as np
def is_valid(board, row, col, num):
"""Kiểm tra xem số 'num' có thể đặt vào ô (row, col) không"""
if num in board[row]: # Kiểm tra hàng
return False
if num in board[:, col]: # Kiểm tra cột
return False
box_x, box_y = (row // 3) * 3, (col // 3) * 3... | Python | 1 |
videos目录
raw_videos_dir = os.path.join(dataset_path, "raw_videos")
# 场景输出目录应该在数据集下的scenes目录
scenes_dir = os.path.join(dataset_path, "scenes")
# 检查原始视频目录下是否有视频文件
raw_videos = []
video_extensions = [".mp4", ".avi", ".mov", ".mkv"]
video_files = []
f... | Python | 1 |
f _get_nft_code(self, name: str, symbol: str, base_uri: str,
is_burnable: bool, is_pausable: bool) -> str:
"""Get customized NFT contract code."""
with open('src/blockchain/smart_contracts/erc721.py', 'r') as f:
code = f.read()
# Customize features
... | Python | 1 |
edges):
r"""Topologically sort based on a user provided edge definition.
Args:
graph: A list of node names.
get_edges: A function mapping from node name to a hashable collection
of node names which this node has outgoing edges to.
Returns:
A list containing all of the node in graph in ... | Python | 1 |
"""Intermediate Traffic API."""
from typing import Self
from tomtom_apis.api import BaseApi
class IntermediateTrafficApi(BaseApi):
"""Intermediate Traffic API.
The mission of TomTom is helping our customers arrive at their destinations faster, more safely and more reliably, regardless of their locations.
... | Python | 1 |
color2.0 + m;
let green = color2.1 + m;
let blue = color2.2 + m;
Color32::from_rgb(
(red * 255.0) as u8,
(green * 255.0) as u8,
(blue * 255.0) as u8,
)
}
<filename>src/tui/mod.rs
//! TUI Splash Core
//!
//! TUI splash procedure core. Dictates the TUI windows and operations.
pub... | Rust | 0 |
size_of::<packed::Packed>(),
)
}
}
}
mod packed {
use crate::dx12::pipeline_state_stream::PackedPipelineStateStreamObject;
use windows::Win32::Graphics::Direct3D12::{
ID3D12RootSignature, D3D12_BLEND_DESC, D3D12_CACHED_PIPELINE_STATE,
D3D12_DEPTH_STENCIL... | Rust | 0 |
sed.
return True
def handle(self, exc):
"""Do something with the current exception.
Args:
exc: Exception, the current exception
This method must be overridden.
"""
raise NotImplementedError()
def install_exception_handler(handler):
"""Installs an exception handler.
Args:
ha... | Python | 1 |
: Vec<Score>,
pub higher: Vec<Score>,
}
pub fn scores(user_score: &Score, conn: &PgConnection) -> QueryResult<Scores> {
let (higher, lower) = user_score.neighbours(&conn)?;
Ok(Scores {
placement: user_score.placement(conn)?,
top_three: Score::top_three(conn)?,
lower,
higher... | Rust | 0 |
0x1e, 0x84, 0x95, 0xaf, 0x13, 0x50,
0x8b,
];
assert_eq!(&pkt_iv, &expected_server_pkt_iv);
assert!(derive_hdr_key(aead, &secret, &mut hdr_key).is_ok());
let expected_server_hdr_key = [
0xa8, 0xed, 0x82, 0xe6, 0x66, 0x4f, 0x86, 0x5a, 0xed, 0xf6, 0x10,
... | Rust | 0 |
>>> f = (4*k + 1)*factorial(k)/factorial(2*k + 1)
>>> gosper_sum(f, (k, 0, n))
(-factorial(n) + 2*factorial(2*n + 1))/factorial(2*n + 1)
>>> _.subs(n, 2) == sum(f.subs(k, i) for i in [0, 1, 2])
True
>>> gosper_sum(f, (k, 3, n))
(-60*factorial(n) + factorial(2*n + 1))/(60*factorial(2*n + 1))
... | Python | 1 |
"""
Точка входа для агента
"""
import asyncio
import typer
from rich.console import Console
from rich.panel import Panel
from agent_langgraph.models import AnalysisResult
from common.exceptions import print_exception
from .agent import run_security_scan
app = typer.Typer()
console = Console()
@app.command()
def ... | Python | 1 |
ory id in the original dataset, mainly
# used for evaluation.
# - contiguous category id: [0, #classes), in order to train the linear
# softmax classifier.
# in order to use sem_seg evaluator
return meta
_PREDEFINED_SPLITS_PANOVSPW = {
"panoVSPW_vps_video_train": (
... | Python | 1 |
)
} else {
None
}
}
// Guard ID to total number of asleep minutes by the minute number
fn get_asleep_minutes(input: &str) -> BTreeMap<usize, [usize; 60]> {
let mut input_lines: Vec<&str> = input.lines().collect();
input_lines.sort_unstable();
lazy_static! {
static ref SHIFT_CHANGE_... | Rust | 0 |
import os
import urllib.parse
from typing import Dict
import asyncio
from .cloud_api import get_file_info, get_file_list, get_file_download_url
from .config_manager import config_manager
from .utils import download_file
from . import logger
class StrmGenerator:
"""
strm文件生成器 - 负责根据云盘文件信息生成对应的strm文件
"""
... | Python | 1 |
d"):
return fields_to_store
# Fetch all parent partners and children recursively to get partners from the same company
partners = self.livechat_customer_partner_ids
while True:
new_partners = partners | partners.parent_id
if partners == new_partners:
... | Python | 1 |
import math
from torch import nn
from torch.autograd import Function
import torch
import pyDeform
device = None
class GraphLoss2Function(Function):
@staticmethod
def forward(ctx, V1, E1, rigidity2, param_id1, param_id2):
global device
pid1 = param_id1.tolist()
pid2 = param_id2.tolist()
test_V1 = torch.from... | Python | 1 |
field0: "flapjacks are fun?".to_string(),
field1: 42,
});
println!("value1: {:#?}", value1);
let delta = value0.delta(&value1).unwrap();
println!("delta: {:#?}", delta);
let expected: RwLockDelta<Foo> = RwLockDelta(Some(FooDelta {
field0: Some(
"flapjacks are fun?".to_s... | Rust | 0 |
import json
import sys
try:
from lanzou.api import LanZouCloud
except:
print('missing package: pip3 install lanzou-api')
exit(1)
def show_progress(file_name, total_size, now_size):
"""显示进度的回调函数"""
percent = now_size / total_size
bar_len = 40 # 进度条长总度
bar_str = '>' * round(bar_len * percent... | Python | 1 |
on Ubuntu 18.4
"""
self.assertEqual(jc.parsers.arp.parse(self.ubuntu_18_4_arp, quiet=True), self.ubuntu_18_4_arp_json)
def test_arp_a_centos_7_7(self):
"""
Test 'arp -a' on Centos 7.7
"""
self.assertEqual(jc.parsers.arp.parse(self.centos_7_7_arp_a, quiet=True), self.... | Python | 1 |
| Targets::GLSL | Targets::DOT | Targets::WGSL,
),
("boids", Targets::SPIRV | Targets::METAL | Targets::GLSL),
("skybox", Targets::SPIRV | Targets::METAL | Targets::GLSL),
(
"collatz",
Targets::SPIRV | Targets::METAL | Targets::IR | Targets::ANALYSIS,
),
... | Rust | 0 |
ow_temp(t, n[0]))
.collect()
)
}
#[inline]
fn pow_temp(x: f64, y: AD) -> AD {
AD1(x.powf(y.x()), x.powf(y.x()) * x.ln() * y.dx())
}
use std::{collections::HashMap, hash::Hash, net::SocketAddr};
use serde::Serialize;
use crate::{components::chainspec_loader::ChainspecInfo, types::Block};
/// Data... | Rust | 0 |
aderBytesBuilder::new();
// https://github.com/BurntSushi/ripgrep/blob/a7d26c8f144a4957b75f71087a66692d0b25759a/grep-searcher/src/searcher/mod.rs#L706
let inp = decode_builder
.encoding(encoding)
.utf8_passthru(true)
.strip_bom(bom_sniffing)
.bom_override(true)
.bom_sniff... | Rust | 0 |
metadata,
search_scope=self.search_scope,
search_type=self.search_type,
mmr_lambda=self.mmr_lambda,
)
results: List[MemorySearchResult] = self.zep_client.memory.search_memory(
self.session_id, payload, limit=self.top_k
)
if self.search_sc... | Python | 1 |
# Matrix Search
# https://www.interviewbit.com/problems/matrix-search/
#
# Write an efficient algorithm that searches for a value in an m x n matrix.
#
# This matrix has the following properties:
#
# Integers in each row are sorted from left to right.
# The first integer of each row is greater than or e... | Python | 1 |
), &mut noise, &mut buf).await;
let len = handle_read_shake(circuit_conn.in_channel_receiver.lock().await.next().await.unwrap(), &mut noise, &mut buf);
//verify
let pubkey = noise.get_remote_static().unwrap();
let verify_success = crate::network::utils::handle_remote_handshake_payload(... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
import json
import re
from utils import *
def lookup(word, *args):
params = {
'key': 'E93A321FB1995DF5EC118B51ABAF8DC7',
'type': 'json',
'w': word.lower()
}
url = '{}?{}'.format('http://dict-co.iciba.com/api/dictionary.ph... | Python | 1 |
_bytes(&self) -> usize {
sucds::util::vec_io::size_in_bytes(&self.data)
}
fn memory_statistics(&self) -> serde_json::Value {
let data = sucds::util::vec_io::size_in_bytes(&self.data);
serde_json::json!({ "data": data })
}
#[inline(always)]
fn get(&self, token: Gram) -> Opti... | Rust | 0 |
import pika, json
params = pika.URLParameters('your_rabbitmq_url')
connection = pika.BlockingConnection(params)
channel = connection.channel()
def publish(method, body):
properties = pika.BasicProperties(method)
channel.basic_publish(exchange='', routing_key='admin', body=json.dumps(body), properties=prope... | Python | 1 |
.nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, padding=1)
def forward(self, x):
x = self.conv(x)
return x
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
model = Net()
model = model.eval()
print... | Python | 1 |
;
let actual = a + b;
assert_eq!(expected, actual);
}
#[test]
fn impl_sub_for_f64x2() {
let a = f64x2::from([1.0, 2.0]);
let b = f64x2::from([5.0, -10.0]);
let expected = f64x2::from([-4.0, 12.0]);
let actual = a - b;
assert_eq!(expected, actual);
}
#[test]
fn impl_mul_for_f64x2() {
let a = f64x2::fro... | Rust | 0 |
s = asyncio.run(
parallel_compute_score_async(self.compute_score,
sequences_str,
ground_truth,
data_sources,
extra_info=extr... | Python | 1 |
pos) | LtacArg::FltReg64(pos) => {
let reg = riscv64_op_freg(*pos);
line.push_str(®);
},
LtacArg::RetRegI8 | LtacArg::RetRegU8 |
LtacArg::RetRegI16 | LtacArg::RetRegU16 |
LtacArg::RetRegI32 | LtacArg::RetRegU32 |
LtacArg::RetRegI64 | LtacArg::RetRegU64... | Rust | 0 |
ion_times[name], per_sample_times[name]])
# Display Results in a Table
results_df = pd.DataFrame(results, columns=["Model", "Accuracy", "Precision", "Recall", "F1-score", "Total Prediction Time (s)", "Prediction Time per Sample (s)"])
st.write(results_df)
# Find Best Model
best... | Python | 1 |
# LoRaWAN Security Framework - SessionKeysGenerator
# Copyright (c) 2019 IOActive Inc. All rights reserved.
import os, sys, argparse, json
import lorawanwrapper.LorawanWrapper as LorawanWrapper
if __name__ == '__main__':
print ("\n*****************************************************")
print ("LoRaWAN Securi... | Python | 1 |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
"""Basic example which iter... | Python | 1 |
/// Efficient implementation of self -= ((1/s)*other)
fn sub_scalar_ldivide(&mut self, other: impl Borrow<Self>, rational: impl Into<Self::RationalType>) -> &mut Self
{
self.sub_inplace(other.borrow().scalar_ldivide(rational))
}
}
// This file was generated by gir (https://github.com/gtk-r... | Rust | 0 |
# Simple crawler on curated streams and delays to get you started
# New video tutorials are available at https://www.microprediction.com/python-1 to help you
# get started creating streams and/or submitting predictions.
from microprediction.crawler import MicroCrawler
CURATED = ['bart_delays.json', 'altitude.json', '... | Python | 1 |
if scriptpath in scriptPaths}
# Export the responses of the current function call to the desired target folder
self.export_results(export_folder = export_folder)
# Reset the results variable to contain all responses agai... | Python | 1 |
f.actor_new(obs,
rnn_states_actor,
masks,
available_actions,
... | Python | 1 |
from policyengine_us.model_api import *
class CCDFDurationOfCare(Enum):
WEEKLY = "Weekly"
DAILY = "Daily"
PART_DAY = "Part-Day"
HOURLY = "Hourly"
class ccdf_duration_of_care(Variable):
value_type = Enum
possible_values = CCDFDurationOfCare
default_value = CCDFDurationOfCare.WEEKLY
en... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.